diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 809b8b7f6a74d..1f57b784a31da 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -38,7 +38,7 @@ use thin_vec::{ThinVec, thin_vec}; use crate::attr::data_structures::CfgEntry; pub use crate::format::*; use crate::token::{self, CommentKind, Delimiter}; -use crate::tokenstream::{DelimSpan, LazyAttrTokenStream, TokenStream}; +use crate::tokenstream::{DelimSpan, LazyAttrTokenStream}; use crate::util::parser::{ExprPrecedence, Fixity}; use crate::visit::{AssocCtxt, BoundKind, LifetimeCtxt}; @@ -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)] @@ -2090,11 +2091,11 @@ impl AttrArgs { /// Tokens inside the delimiters or after `=`. /// Proc macros see these tokens, for example. - pub fn inner_tokens(&self) -> TokenStream { + pub fn inner_tokens(&self) -> ArenaTokenStream { match self { - AttrArgs::Empty => TokenStream::default(), + AttrArgs::Empty => ArenaTokenStream::default(), AttrArgs::Delimited(args) => args.tokens.clone(), - AttrArgs::Eq { expr, .. } => TokenStream::from_ast(expr), + AttrArgs::Eq { expr, .. } => ArenaTokenStream::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 { @@ -4494,7 +4495,7 @@ mod size_asserts { static_assert_size!(MetaItem, 80); static_assert_size!(MetaItemKind, 40); static_assert_size!(MetaItemLit, 40); - static_assert_size!(NormalAttr, 80); + static_assert_size!(NormalAttr, 96); static_assert_size!(Param, 40); static_assert_size!(Pat, 64); static_assert_size!(PatKind, 48); diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 40a1b4bd32218..8951a5a91fa0f 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -19,9 +19,12 @@ use crate::ast::{ use crate::token::{ self, CommentKind, Delimiter, DocFragmentKind, InvisibleOrigin, MetaVarKind, Token, }; +use crate::tokenarena::{ + ArenaTokenStream, ArenaTokenStreamBuilder, ArenaTokenTree, ArenaTokenTreeIter, DelimitedData, +}; use crate::tokenstream::{ AttrTokenStream, AttrTokenTree, DelimSpacing, DelimSpan, LazyAttrTokenStream, Spacing, - TokenStream, TokenStreamIter, TokenTree, + TokenTree, }; use crate::util::comments; use crate::util::literal::escape_string_symbol; @@ -308,6 +311,25 @@ impl Attribute { } } + pub fn push_token_trees(&self, builder: &mut ArenaTokenStreamBuilder) { + match self.kind { + AttrKind::Normal(ref normal) => { + normal + .tokens + .as_ref() + .unwrap_or_else(|| panic!("attribute is missing tokens: {self:?}")) + .to_attr_token_stream() + .push_token_trees(builder); + } + // Empty tokens here ensures synthetic attributes are invisible to proc macros. + AttrKind::Synthetic(..) => {} + AttrKind::DocComment(comment_kind, data) => builder.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 +367,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) } AttrArgs::Delimited(_) | AttrArgs::Eq { .. } | AttrArgs::Empty => None, } @@ -475,16 +497,16 @@ impl MetaItem { } } - fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option { + fn from_tokens(iter: &mut ArenaTokenTreeIter<'_>) -> Option { // FIXME: Share code with `parse_path`. - let tt = iter.next().map(|tt| TokenTree::uninterpolate(tt)); + let tt = iter.next().map(|tt| ArenaTokenTree::uninterpolate(tt)); let path = match tt.as_deref() { - Some(&TokenTree::Token( + Some(&ArenaTokenTree::Token( Token { kind: ref kind @ (token::Ident(..) | token::PathSep), span }, _, )) => 'arm: { let mut segments = if let &token::Ident(name, _) = kind { - if let Some(TokenTree::Token(Token { kind: token::PathSep, .. }, _)) = + if let Some(ArenaTokenTree::Token(Token { kind: token::PathSep, .. }, _)) = iter.peek() { iter.next(); @@ -496,13 +518,16 @@ impl MetaItem { thin_vec![PathSegment::path_root(span)] }; loop { - let Some(&TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) = - iter.next().map(|tt| TokenTree::uninterpolate(tt)).as_deref() + let Some(&ArenaTokenTree::Token( + Token { kind: token::Ident(name, _), span }, + _, + )) = iter.next().map(|tt| ArenaTokenTree::uninterpolate(tt)).as_deref() else { return None; }; segments.push(PathSegment::from_ident(Ident::new(name, span))); - let Some(TokenTree::Token(Token { kind: token::PathSep, .. }, _)) = iter.peek() + let Some(ArenaTokenTree::Token(Token { kind: token::PathSep, .. }, _)) = + iter.peek() else { break; }; @@ -511,18 +536,21 @@ impl MetaItem { let span = span.with_hi(segments.last().unwrap().ident.span.hi()); Path { span, segments } } - Some(TokenTree::Delimited( - _span, - _spacing, - Delimiter::Invisible(InvisibleOrigin::MetaVar( - MetaVarKind::Meta { .. } | MetaVarKind::Path, - )), - _stream, + Some(ArenaTokenTree::DelimitedStart( + _, + DelimitedData { + delimiter: + Delimiter::Invisible(InvisibleOrigin::MetaVar( + MetaVarKind::Meta { .. } | MetaVarKind::Path, + )), + span: _, + spacing: _, + }, )) => { // This path is currently unreachable in the test suite. unreachable!() } - Some(TokenTree::Token(Token { kind, .. }, _)) if kind.is_delim() => { + Some(ArenaTokenTree::Token(Token { kind, .. }, _)) if kind.is_delim() => { panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tt); } _ => return None, @@ -544,41 +572,50 @@ impl MetaItem { impl MetaItemKind { // public because it can be called in the hir - pub fn list_from_tokens(tokens: TokenStream) -> Option> { - let mut iter = tokens.iter(); + pub fn list_from_tokens(tokens: &ArenaTokenStream) -> Option> { + let mut iter = tokens.iter_top_level_trees(); let mut result = ThinVec::new(); while iter.peek().is_some() { let item = MetaItemInner::from_tokens(&mut iter)?; result.push(item); match iter.next() { - None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {} + None | Some(ArenaTokenTree::Token(Token { kind: token::Comma, .. }, _)) => {} _ => return None, } } Some(result) } - fn name_value_from_tokens(iter: &mut TokenStreamIter<'_>) -> Option { + fn name_value_from_tokens(iter: &mut ArenaTokenTreeIter<'_>) -> Option { match iter.next() { - Some(TokenTree::Delimited(.., Delimiter::Invisible(_), inner_tokens)) => { - MetaItemKind::name_value_from_tokens(&mut inner_tokens.iter()) - } - Some(TokenTree::Token(token, _)) => { + Some(ArenaTokenTree::DelimitedStart( + bounds, + DelimitedData { delimiter: Delimiter::Invisible(_), .. }, + )) => MetaItemKind::name_value_from_tokens( + &mut iter.stream().iter_delimited_contents(bounds), + ), + Some(ArenaTokenTree::Token(token, _)) => { MetaItemLit::from_token(token).map(MetaItemKind::NameValue) } _ => None, } } - fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option { + fn from_tokens(iter: &mut ArenaTokenTreeIter<'_>) -> Option { match iter.peek() { - Some(TokenTree::Delimited(.., Delimiter::Parenthesis, inner_tokens)) => { - let inner_tokens = inner_tokens.clone(); + Some(ArenaTokenTree::DelimitedStart( + bounds, + DelimitedData { delimiter: Delimiter::Parenthesis, .. }, + )) => { iter.next(); - MetaItemKind::list_from_tokens(inner_tokens).map(MetaItemKind::List) + MetaItemKind::list_from_tokens(&ArenaTokenStream::separate_delimited_inner( + *bounds, + iter.stream(), + )) + .map(MetaItemKind::List) } - Some(TokenTree::Delimited(..)) => None, - Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => { + Some(ArenaTokenTree::DelimitedStart(..)) => None, + Some(ArenaTokenTree::Token(Token { kind: token::Eq, .. }, _)) => { iter.next(); MetaItemKind::name_value_from_tokens(iter) } @@ -590,7 +627,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).map(MetaItemKind::List) } AttrArgs::Delimited(..) => None, AttrArgs::Eq { expr, .. } => match expr.kind { @@ -705,15 +742,19 @@ impl MetaItemInner { self.meta_item().is_some() } - fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option { + fn from_tokens(iter: &mut ArenaTokenTreeIter<'_>) -> Option { match iter.peek() { - Some(TokenTree::Token(token, _)) if let Some(lit) = MetaItemLit::from_token(token) => { + Some(ArenaTokenTree::Token(token, _)) + if let Some(lit) = MetaItemLit::from_token(token) => + { iter.next(); return Some(MetaItemInner::Lit(lit)); } - Some(TokenTree::Delimited(.., Delimiter::Invisible(_), inner_tokens)) => { + Some(ArenaTokenTree::DelimitedStart(bounds, _)) => { iter.next(); - return MetaItemInner::from_tokens(&mut inner_tokens.iter()); + return MetaItemInner::from_tokens( + &mut iter.stream().iter_delimited_contents(bounds), + ); } _ => {} } @@ -803,10 +844,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_iter(std::iter::once(( 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..73c6295031dbc --- /dev/null +++ b/compiler/rustc_ast/src/tokenarena.rs @@ -0,0 +1,983 @@ +use std::borrow::Cow; +use std::fmt; +use std::hash::{Hash, Hasher}; +use std::num::NonZeroU32; +use std::sync::{Arc, LazyLock}; + +use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher}; +use rustc_index::static_assert_size; +use rustc_macros::{Decodable, Encodable, StableHash}; +use rustc_serialize::{Decodable, Encodable}; +use rustc_span::{Span, SpanDecoder, SpanEncoder}; + +use crate::token::{Delimiter, Token, TokenKind}; +use crate::tokenstream::{ + DelimSpacing, DelimSpan, LazyAttrTokenStream, Spacing, TokenStream, TokenTree, +}; +use crate::{Attribute, HasTokens}; + +/// Part of a `TokenArena`. +#[derive(Debug, Copy, Clone)] +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. + #[inline] + pub fn token_alone(kind: TokenKind, span: Span) -> ArenaTokenTree { + ArenaTokenTree::Token(Token::new(kind, span), Spacing::Alone) + } + + /// Create a `TokenTree::Token` with joint spacing. + #[inline] + pub fn token_joint(kind: TokenKind, span: Span) -> ArenaTokenTree { + ArenaTokenTree::Token(Token::new(kind, span), Spacing::Joint) + } + + pub fn uninterpolate(&self) -> Cow<'_, ArenaTokenTree> { + match self { + ArenaTokenTree::Token(token, spacing) => match token.uninterpolate() { + Cow::Owned(token) => Cow::Owned(ArenaTokenTree::Token(token, *spacing)), + Cow::Borrowed(_) => Cow::Borrowed(self), + }, + _ => Cow::Borrowed(self), + } + } + + /// 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_contents(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(), + } + } + + #[inline] + pub fn to_delimited_data(&self) -> Option<&DelimitedData> { + match self { + ArenaTokenTree::Token(_, _) => None, + ArenaTokenTree::DelimitedStart(_, data) => Some(data), + } + } + + #[inline] + pub fn to_delimited_bounds(&self) -> Option<&DelimitedBounds> { + match self { + ArenaTokenTree::Token(_, _) => None, + ArenaTokenTree::DelimitedStart(bounds, _) => Some(bounds), + } + } +} + +static_assert_size!(ArenaTokenTree, 44); + +#[derive(Debug, Default)] +pub struct ArenaTokenStreamBuilder { + tokens: Vec, + /// Index of the current delimited sequence + current_delimited_sequence: Option, + /// This is only useful to optimize glueing + last_push_was_token: bool, +} + +impl ArenaTokenStreamBuilder { + pub fn with_capacity(capacity: usize) -> Self { + Self { + tokens: Vec::with_capacity(capacity), + current_delimited_sequence: None, + last_push_was_token: false, + } + } + + pub fn tokens(&self) -> &[ArenaTokenTree] { + &self.tokens + } + + #[inline] + pub fn push_token(&mut self, token: Token, spacing: Spacing) { + self.tokens.push(ArenaTokenTree::Token(token, spacing)); + self.last_push_was_token = true; + } + + #[inline] + pub fn push_token_alone(&mut self, token: Token) { + self.push_token(token, Spacing::Alone); + } + + pub fn push_token_tree(&mut self, tt: &ArenaTokenTree, stream: &ArenaTokenStream) { + match tt { + ArenaTokenTree::Token(token, spacing) => { + self.push_token(*token, *spacing); + } + ArenaTokenTree::DelimitedStart(bounds, data) => { + self.push_delimited( + |builder| { + builder.fill_stream(stream.iter_delimited_contents(bounds)); + }, + *data, + ); + } + } + } + + pub fn push_iter(&mut self, iter: ArenaTokenTreeIter<'_>) { + self.fill_stream(iter); + } + + pub fn push_stream(&mut self, stream: ArenaTokenStream) { + self.tokens.reserve(stream.length()); + self.fill_stream(stream.iter_top_level_trees()); + } + + pub fn pop(&mut self) -> Option { + // Note: calling this function is fine even if we are within a delimited sequence. + let tree = self.tokens.pop(); + if let Some(tree) = &tree { + assert!(matches!(tree, ArenaTokenTree::Token(..))); + } + tree + } + + // If `self` is not empty, try to glue `tt` onto its last top-level token. The return + // value indicates if gluing took place. + pub fn try_glue_to_last_top_level_token(&mut self, token: &Token, spacing: Spacing) -> bool { + assert!(self.current_delimited_sequence.is_none()); + if let Some(ArenaTokenTree::Token(last_tok, Spacing::Joint | Spacing::JointHidden)) = + self.tokens.last() + // We can only do this if the last tree is a top-level token within the current + // delimited sequence. + // If there is no last top-level sequence, then the last token has to be top-level + && self.last_push_was_token + && let Some(glued_tok) = last_tok.glue(&token) + { + // ...then overwrite the last token tree in `vec` with the glued token. + *self.tokens.last_mut().unwrap() = ArenaTokenTree::Token(glued_tok, spacing); + true + } else { + false + } + } + + pub fn push_delimited(&mut self, func: F, data: DelimitedData) -> R + where + F: FnOnce(&mut Self) -> R, + { + let start = self.start_delimited(); + let ret = func(self); + self.close_delimited(start, data); + ret + } + + pub fn start_delimited(&mut self) -> OpenDelimited { + let index = AbsoluteTokenTreeIndex(self.length() as u32); + let parent = self.current_delimited_sequence.replace(index); + + self.tokens.push(ArenaTokenTree::DelimitedStart( + DelimitedBounds { + start: index, + length: NonZeroU32::MIN, + parent, + last_push_was_token: false, + }, + 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 last_push_was_token = self.last_push_was_token; + self.last_push_was_token = false; + + let length = self.length(); + match &mut self.tokens[open.start.as_usize()] { + ArenaTokenTree::Token(..) => { + unreachable!("Called close_delimited on a token"); + } + ArenaTokenTree::DelimitedStart(bounds, data) => { + let len = length.saturating_sub(open.start.as_usize()); + bounds.length = NonZeroU32::new(len as u32).unwrap(); + *data = delimited_data; + self.current_delimited_sequence = bounds.parent; + bounds.last_push_was_token = last_push_was_token; + } + } + } + + pub fn empty_delimited(&mut self, data: DelimitedData) { + self.push_delimited(|_builder| {}, data); + } + + /// Copy `stream` into this builder, while possibly adding additional tokens or skipping + /// existing tokens. + pub fn build_from_stream(&mut self, stream: &ArenaTokenStream, mut func: F) + where + F: FnMut(&mut Self, &ArenaTokenTree) -> PerTreeOp, + { + fn fill( + builder: &mut ArenaTokenStreamBuilder, + func: &mut dyn FnMut(&mut ArenaTokenStreamBuilder, &ArenaTokenTree) -> PerTreeOp, + tree: &ArenaTokenTree, + stream: &ArenaTokenStream, + ) { + match func(builder, tree) { + PerTreeOp::Continue => {} + PerTreeOp::Skip => { + return; + } + } + match tree { + ArenaTokenTree::Token(token, spacing) => { + builder.push_token(*token, *spacing); + } + ArenaTokenTree::DelimitedStart(bounds, data) => { + builder.push_delimited( + |builder| { + fill_iter(builder, func, stream.iter_delimited_contents(bounds)); + }, + *data, + ); + } + } + } + fn fill_iter( + builder: &mut ArenaTokenStreamBuilder, + func: &mut dyn FnMut(&mut ArenaTokenStreamBuilder, &ArenaTokenTree) -> PerTreeOp, + iter: ArenaTokenTreeIter<'_>, + ) { + let stream = iter.stream().clone(); + for tree in iter { + fill(builder, func, tree, &stream); + } + } + fill_iter(self, &mut func, stream.iter_top_level_trees()); + } + + /// Insert trees from `builder` at the start of a delimited sequence specified by + /// `bounds`. + pub fn insert_at_start_of_delimited( + &mut self, + bounds: DelimitedBounds, + builder: ArenaTokenStreamBuilder, + ) { + let start = bounds.start; + let Some(ArenaTokenTree::DelimitedStart(..)) = self.get_innermost_elem_at(start) else { + panic!("insert_at_start_of_delimited called with invalid bounds"); + }; + // Insert the trees + let inserted_len = builder.tokens.len() as u32; + let after_insertion = bounds.start.0 + 1 + inserted_len; + self.tokens.splice(start.as_usize() + 1..start.as_usize() + 1, builder.tokens); + + // Fix-up the start indices and parents after what was inserted + for tree in &mut self.tokens[after_insertion as usize..] { + match tree { + ArenaTokenTree::Token(_, _) => {} + ArenaTokenTree::DelimitedStart(b, _) => { + b.start = AbsoluteTokenTreeIndex(b.start.0 + inserted_len); + b.parent = b.parent.map(|p| { + if p > start { AbsoluteTokenTreeIndex(p.0 + inserted_len) } else { p } + }); + } + } + } + + let start = start.as_usize(); + // Fix-up the length of trees before what was inserted, including the current delimited + // sequence. + for tree in self.tokens[..start + 1].iter_mut().rev() { + match tree { + ArenaTokenTree::Token(_, _) => {} + ArenaTokenTree::DelimitedStart(b, _) => { + if b.index_of_next_token_tree().as_usize() > start { + b.length = b.length.checked_add(inserted_len).unwrap(); + } + } + } + } + + // Fix-up the start indices and parents in what was inserted + let offset = bounds.start().next_index(); + for tree in &mut self.tokens[start + 1..after_insertion as usize] { + match tree { + ArenaTokenTree::Token(_, _) => {} + ArenaTokenTree::DelimitedStart(b, _) => { + b.start = AbsoluteTokenTreeIndex(b.start.0 + offset.0); + b.parent = Some(match b.parent { + Some(p) => AbsoluteTokenTreeIndex(p.0 + offset.0), + None => { + // Reparent the inserted top-level delimited sequences to the current + // delimited sequence + bounds.start + } + }); + } + } + } + } + + #[inline] + pub fn get_innermost_elem_at(&self, index: AbsoluteTokenTreeIndex) -> Option<&ArenaTokenTree> { + self.tokens.get(index.as_usize()) + } + + #[inline] + pub fn current_index(&self) -> AbsoluteTokenTreeIndex { + AbsoluteTokenTreeIndex(self.length() as u32) + } + + #[inline] + pub fn tree_count_since(&self, index: AbsoluteTokenTreeIndex) -> u32 { + self.current_index().0.saturating_sub(index.0) + } + + #[inline] + pub fn finish(self) -> ArenaTokenStream { + assert!(self.current_delimited_sequence.is_none()); + if self.tokens.is_empty() { + ArenaTokenStream::default() + } else { + let range = TokenTreeRange::full(&self.tokens); + ArenaTokenStream { + tokens: Arc::new(self.tokens), + range, + last_push_was_token: self.last_push_was_token, + } + } + } + + #[inline] + pub fn length(&self) -> usize { + self.tokens.len() + } + + fn fill_stream(&mut self, iter: ArenaTokenTreeIter<'_>) { + let stream = iter.stream().clone(); + self.tokens.reserve(iter.length()); + for tt in iter { + self.push_token_tree(tt, &stream); + } + } +} + +pub enum PerTreeOp { + /// Continue processing the tree as normally. + Continue, + /// Skip the tree, do not insert it. + Skip, +} + +/// A shared empty token stream, used to avoid an unnecessary `Arc` allocation for every empty +/// token stream. +static EMPTY_TOKEN_STREAM: LazyLock = LazyLock::new(|| ArenaTokenStream { + tokens: Arc::new(Vec::new()), + range: TokenTreeRange::empty(), + last_push_was_token: false, +}); + +#[derive(Clone, Debug)] +pub struct ArenaTokenStream { + tokens: Arc>, + range: TokenTreeRange, + last_push_was_token: bool, +} + +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_iter(tokens: I) -> Self + where + I: IntoIterator, + { + let tokens = Arc::new( + tokens + .into_iter() + .map(|(token, spacing)| ArenaTokenTree::Token(token, spacing)) + .collect::>(), + ); + let range = TokenTreeRange::full(&tokens); + Self { tokens, range, last_push_was_token: true } + } + + /// 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 { + builder.push_token_tree(tree, stream); + } + builder.finish() + } + + pub fn from_ast(node: &(impl HasTokens + fmt::Debug)) -> Self { + let tokens = node.tokens().unwrap_or_else(|| panic!("missing tokens for node: {:?}", node)); + let mut builder = ArenaTokenStreamBuilder::default(); + attrs_and_tokens_to_token_trees_arena(node.attrs(), tokens, &mut builder, 0); + builder.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) + } + + /// Try to reuse the tokens of this stream into a builder, if we are the only copy. + /// If it is not the only copy, clones the inner tokens. + pub fn into_builder(self) -> ArenaTokenStreamBuilder { + // Reuse the whole thing + if self.range.start.0 == 0 && self.range.end.0 == self.tokens.len() as u32 { + let last_push_was_token = self.last_push_was_token; + ArenaTokenStreamBuilder { + tokens: self.try_take_tokens(), + current_delimited_sequence: None, + last_push_was_token, + } + } else { + // Copy out the given range + let mut builder = ArenaTokenStreamBuilder::with_capacity(self.range.len()); + builder.push_stream(self); + builder + } + } + + /// Try to reuse the tokens of this stream, if we are the only copy. + /// If it is not the only copy, clones the inner tokens. + fn try_take_tokens(mut self) -> Vec { + let tokens = Arc::make_mut(&mut self.tokens); + std::mem::take(tokens) + } + + /// Create a token stream containing a single token with alone spacing. The + /// spacing used for the final token in a constructed stream doesn't matter + /// because it's never used. In practice we arbitrarily use + /// `Spacing::Alone`. + pub fn token_alone(kind: TokenKind, span: Span) -> Self { + Self { + tokens: Arc::new(vec![ArenaTokenTree::token_alone(kind, span)]), + range: TokenTreeRange::single(), + last_push_was_token: true, + } + } + + /// 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 { + if bounds.is_empty() { + return Self::default(); + } + let range = TokenTreeRange::from_bounds_contents(&bounds); + Self { + tokens: stream.tokens.clone(), + range, + last_push_was_token: bounds.last_push_was_token, + } + } + + #[inline] + pub fn range(&self) -> TokenTreeRange { + self.range + } + + #[inline] + pub fn length(&self) -> usize { + self.range.len() + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.range.is_empty() + } + + #[inline] + pub fn get_parent_of(&self, bounds: DelimitedBounds) -> Option { + let parent = bounds.parent?; + match self.get_innermost_elem_at(parent) { + Some(ArenaTokenTree::Token(..)) => { + panic!("DelimitedBounds parent index points to a token. This is a bug."); + } + Some(ArenaTokenTree::DelimitedStart(bounds, _)) => Some(*bounds), + None => None, + } + } + + #[inline] + pub fn get_innermost_elem_at(&self, index: AbsoluteTokenTreeIndex) -> Option<&ArenaTokenTree> { + if !self.range.contains(index) { + return None; + } + self.tokens.get(index.as_usize()) + } + + /// Iterate top-level token trees of a delimited token sequence. + /// Does not return the delimited sequence start itself. + pub fn iter_delimited_contents(&self, bounds: &DelimitedBounds) -> ArenaTokenTreeIter<'_> { + ArenaTokenTreeIter::new_delimited_contents(self, bounds) + } + + /// Iterate over the delimited token sequence. + /// Return the delimited sequence start itself. + pub fn iter_delimited(&self, bounds: &DelimitedBounds) -> ArenaTokenTreeIter<'_> { + ArenaTokenTreeIter::new_delimited(self, bounds) + } + + /// Iterate over the top-level token trees of the whole stream. + /// Does not recurse into delimited sequences. + pub fn iter_top_level_trees(&self) -> ArenaTokenTreeIter<'_> { + ArenaTokenTreeIter::new_top_level(self) + } + + pub fn iter_all_trees(&self) -> impl Iterator + DoubleEndedIterator { + self.tokens.as_slice()[self.range.start.as_usize()..self.range.end.as_usize()].into_iter() + } + + fn iter_flattened(&self) -> impl Iterator { + let mut index = self.range.start(); + std::iter::from_fn(move || { + let Some(tree) = self.get_innermost_elem_at(index) else { + return None; + }; + index.bump_single(); + let item = match tree { + ArenaTokenTree::Token(token, spacing) => { + FlattenedTokenTree::Token(*token, *spacing) + } + ArenaTokenTree::DelimitedStart(bounds, data) => { + // FIXME: is this correct? do we also have to take parents into account? + FlattenedTokenTree::Delimited { data: *data, length: bounds.length } + } + }; + Some(item) + }) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, StableHash)] +enum FlattenedTokenTree { + Token(Token, Spacing), + Delimited { data: DelimitedData, length: NonZeroU32 }, +} + +impl Default for ArenaTokenStream { + fn default() -> Self { + EMPTY_TOKEN_STREAM.clone() + } +} + +impl PartialEq for ArenaTokenStream { + fn eq(&self, other: &Self) -> bool { + self.iter_flattened().eq(other.iter_flattened()) + } +} + +impl Eq for ArenaTokenStream {} + +impl Hash for ArenaTokenStream { + fn hash(&self, state: &mut H) { + for tree in self.iter_flattened() { + tree.hash(state); + } + } +} + +impl StableHash for ArenaTokenStream { + fn stable_hash(&self, hcx: &mut Hcx, hasher: &mut StableHasher) { + for tree in self.iter_flattened() { + tree.stable_hash(hcx, hasher); + } + } +} + +impl Encodable for ArenaTokenStream { + fn encode(&self, encoder: &mut S) { + let size = self.length(); + size.encode(encoder); + for tree in self.iter_flattened() { + tree.encode(encoder); + } + } +} + +impl Decodable for ArenaTokenStream { + fn decode(decoder: &mut D) -> Self { + let mut remaining = usize::decode(decoder); + if remaining == 0 { + return Self::default(); + } + + let mut builder = ArenaTokenStreamBuilder::with_capacity(remaining); + + fn build( + decoder: &mut D, + builder: &mut ArenaTokenStreamBuilder, + remaining: &mut usize, + ) { + if *remaining == 0 { + return; + } + let flattened = FlattenedTokenTree::decode(decoder); + *remaining -= 1; + match flattened { + FlattenedTokenTree::Token(token, spacing) => { + builder.push_token(token, spacing); + } + FlattenedTokenTree::Delimited { data, length } => { + let mut remaining_children = length.get() as usize - 1; + builder.push_delimited( + |builder| { + while remaining_children > 0 { + build(decoder, builder, &mut remaining_children); + } + }, + data, + ); + *remaining -= (length.get() - 1) as usize; + } + } + } + + while remaining > 0 { + build(decoder, &mut builder, &mut remaining); + } + builder.finish() + } +} + +/// Absolute index into a flat list of arena token trees. +#[derive( + Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, StableHash +)] +pub struct AbsoluteTokenTreeIndex(u32); + +impl AbsoluteTokenTreeIndex { + #[inline] + pub fn bump_single(&mut self) { + self.0 += 1; + } + + #[inline] + pub fn bump_delimited(&mut self, bounds: &DelimitedBounds) { + *self = bounds.index_of_next_token_tree(); + } + + #[inline] + pub fn next_index(&self) -> Self { + Self(self.0 + 1) + } + + fn as_usize(self) -> usize { + self.0 as usize + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable)] +pub struct TokenTreeRange { + /// Inclusive + start: AbsoluteTokenTreeIndex, + /// Exclusive + end: AbsoluteTokenTreeIndex, +} + +impl TokenTreeRange { + fn empty() -> Self { + Self { start: AbsoluteTokenTreeIndex(0), end: AbsoluteTokenTreeIndex(0) } + } + + fn full(tokens: &[ArenaTokenTree]) -> Self { + Self { start: AbsoluteTokenTreeIndex(0), end: AbsoluteTokenTreeIndex(tokens.len() as u32) } + } + + fn single() -> Self { + Self { start: AbsoluteTokenTreeIndex(0), end: AbsoluteTokenTreeIndex(1) } + } + + /// Extract a range containing the *contents* of the delimited sequence, without its starting + /// delimiter. + fn from_bounds_contents(bounds: &DelimitedBounds) -> Self { + Self { start: bounds.start.next_index(), end: bounds.index_of_next_token_tree() } + } + + #[inline] + pub fn start(&self) -> AbsoluteTokenTreeIndex { + self.start + } + + #[inline] + pub fn end(&self) -> AbsoluteTokenTreeIndex { + self.end + } + + #[inline] + pub fn one_past_end(&self) -> AbsoluteTokenTreeIndex { + self.end.next_index() + } + + #[inline] + pub fn len(&self) -> usize { + (self.end.0 - self.start.0) as usize + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.start == self.end + } + + #[inline] + fn contains(&self, index: AbsoluteTokenTreeIndex) -> bool { + index >= self.start && index < self.end + } +} + +// Converts multiple attributes and the tokens for a target AST node into token trees, and appends +// them to `res`. +// +// Example: if the AST node is "fn f() { blah(); }", then: +// - Simple if no attributes are present, e.g. "fn f() { blah(); }" +// - Simple if only outer attribute are present, e.g. "#[outer1] #[outer2] fn f() { blah(); }" +// - Trickier if inner attributes are present, because they must be moved within the AST node's +// tokens, e.g. "#[outer] fn f() { #![inner] blah() }" +pub fn attrs_and_tokens_to_token_trees_arena( + attrs: &[Attribute], + target_tokens: &LazyAttrTokenStream, + builder: &mut ArenaTokenStreamBuilder, + start: usize, +) { + let idx = attrs.partition_point(|attr| matches!(attr.style, crate::AttrStyle::Outer)); + let (outer_attrs, inner_attrs) = attrs.split_at(idx); + + // Add outer attribute tokens. + for attr in outer_attrs { + attr.push_token_trees(builder); + } + + // Add target AST node tokens. + target_tokens.to_attr_token_stream().push_token_trees(builder); + + // Insert inner attribute tokens. + if !inner_attrs.is_empty() { + if let Some(bounds) = get_insertion_point( + inner_attrs, + AbsoluteTokenTreeIndex(start as u32), + AbsoluteTokenTreeIndex(builder.tokens.len() as u32), + builder, + ) { + // FIXME: implement this in a more efficient way + let mut inner = ArenaTokenStreamBuilder::default(); + for attribute in inner_attrs { + attribute.push_token_trees(&mut inner); + } + builder.insert_at_start_of_delimited(bounds, inner); + } else { + panic!("Failed to find trailing delimited group in: {builder:?}"); + } + } + + // Inner attributes are only supported on blocks, functions, impls, and + // modules. All of these have their inner attributes placed at the + // beginning of the rightmost outermost braced group: + // e.g. `fn foo() { #![my_attr] }`. (Note: the braces may be within + // invisible delimiters.) + // + // Therefore, we can insert them back into the right location without + // needing to do any extra position tracking. + // + // Note: Outline modules are an exception - they can have attributes like + // `#![my_attr]` at the start of a file. Support for custom attributes in + // this position is not properly implemented - we always synthesize fake + // tokens, so we never reach this code. + fn get_insertion_point( + inner_attrs: &[Attribute], + start: AbsoluteTokenTreeIndex, + end: AbsoluteTokenTreeIndex, + builder: &ArenaTokenStreamBuilder, + ) -> Option { + let is_top_level = + |bounds: &DelimitedBounds| bounds.parent.map(|p| p < start).unwrap_or(true); + + // We need to iterate backwards, only in the range given to us + for tree in builder.tokens[start.as_usize()..end.as_usize()].iter().rev() { + // We need to find only the "top-level" trees in the given range + // We recognize those by them either having no parent, or having a parent that is outside + // the range. + if let ArenaTokenTree::DelimitedStart( + bounds, + DelimitedData { delimiter: Delimiter::Brace, .. }, + ) = tree + { + if !is_top_level(bounds) { + continue; + } + // Found it: the rightmost, outermost braced group. + return Some(*bounds); + } else if let ArenaTokenTree::DelimitedStart( + bounds, + DelimitedData { delimiter: Delimiter::Invisible(_), .. }, + ) = tree + { + if !is_top_level(bounds) { + continue; + } + // Recurse inside invisible delimiters. + // We iterate from the first tree inside of this delimited sequence + let end = bounds.index_of_next_token_tree(); + if let Some(bounds) = + get_insertion_point(inner_attrs, bounds.start().next_index(), end, builder) + { + return Some(bounds); + } + } + } + None + } +} + +#[derive(Clone)] +pub struct ArenaTokenTreeIter<'a> { + stream: &'a ArenaTokenStream, + index: AbsoluteTokenTreeIndex, + end: AbsoluteTokenTreeIndex, +} + +impl<'a> ArenaTokenTreeIter<'a> { + fn new_top_level(stream: &'a ArenaTokenStream) -> Self { + let index = stream.range.start(); + let end = stream.range.end(); + Self { stream, index, end } + } + + fn new_delimited(stream: &'a ArenaTokenStream, bounds: &DelimitedBounds) -> Self { + let index = bounds.start(); + let end = bounds.index_of_next_token_tree(); + Self { stream, index, end } + } + + fn new_delimited_contents(stream: &'a ArenaTokenStream, bounds: &DelimitedBounds) -> Self { + let index = bounds.start().next_index(); + let end = bounds.index_of_next_token_tree(); + Self { stream, index, end } + } + + pub fn stream(&self) -> &'a ArenaTokenStream { + self.stream + } + + // Peeking could be done via `Peekable`, but most iterators need peeking, + // and this is simple and avoids the need to use `peekable` and `Peekable` + // at all the use sites. + pub fn peek(&self) -> Option<&'a ArenaTokenTree> { + if self.index >= self.end { + return None; + } + self.stream.get_innermost_elem_at(self.index) + } + + /// Returns true if the iterator has exactly single tree in it. + pub fn has_single_tree(&self) -> bool { + let mut iter = self.clone(); + if iter.next().is_none() { + return false; + } + iter.next().is_none() + } + + fn length(&self) -> usize { + self.end.as_usize().saturating_sub(self.index.as_usize()) + } +} + +impl<'a> Iterator for ArenaTokenTreeIter<'a> { + type Item = &'a ArenaTokenTree; + + fn next(&mut self) -> Option { + if self.index >= self.end { + return None; + } + let item = self.stream.get_innermost_elem_at(self.index)?; + match item { + token @ ArenaTokenTree::Token(..) => { + self.index.bump_single(); + Some(token) + } + tree @ ArenaTokenTree::DelimitedStart(bounds, _) => { + self.index.bump_delimited(bounds); + Some(tree) + } + } + } +} + +#[must_use] +pub struct OpenDelimited { + start: AbsoluteTokenTreeIndex, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, StableHash)] +pub struct DelimitedBounds { + start: AbsoluteTokenTreeIndex, + /// The length includes both the start token. + /// So an empty delimited sequence has length 1. + length: NonZeroU32, + /// Index of the parent of the current delimited sequence. + /// If this is the root delimited sequence, is `None`. + parent: Option, + last_push_was_token: bool, +} + +impl DelimitedBounds { + #[inline] + pub fn start(&self) -> AbsoluteTokenTreeIndex { + self.start + } + + /// Return the index of the next token tree that follows this delimited token sequence. + #[inline] + pub fn index_of_next_token_tree(&self) -> AbsoluteTokenTreeIndex { + AbsoluteTokenTreeIndex(self.start.0 + self.length.get()) + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.length.get() == 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..709e6b3eb4e41 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -20,6 +20,10 @@ use thin_vec::ThinVec; use crate::ast::AttrStyle; use crate::ast_traits::HasTokens; use crate::token::{self, Delimiter, Token, TokenKind}; +use crate::tokenarena::{ + AbsoluteTokenTreeIndex, ArenaTokenStream, ArenaTokenStreamBuilder, ArenaTokenTree, + DelimitedBounds, DelimitedData, attrs_and_tokens_to_token_trees_arena, +}; use crate::{AttrVec, Attribute}; #[cfg(test)] @@ -470,6 +474,37 @@ impl AttrTokenStream { } res } + + /// Pushes this `AttrTokenStream` to a token builder. During + /// conversion, any `AttrTokenTree::AttrsTarget` gets "flattened" back to a + /// `ArenaTokenStream`, as described in the comment on + /// `attrs_and_tokens_to_token_trees_arena`. + pub fn push_token_trees(&self, builder: &mut ArenaTokenStreamBuilder) { + let start = builder.length(); + for tree in self.0.iter() { + match tree { + AttrTokenTree::Token(inner, spacing) => { + builder.push_token(inner.clone(), *spacing); + } + AttrTokenTree::Delimited(span, spacing, delim, stream) => { + builder.push_delimited( + |builder| { + stream.push_token_trees(builder); + }, + DelimitedData { span: *span, spacing: *spacing, delimiter: *delim }, + ); + } + AttrTokenTree::AttrsTarget(target) => { + attrs_and_tokens_to_token_trees_arena( + &target.attrs, + &target.tokens, + builder, + start, + ); + } + } + } + } } // Converts multiple attributes and the tokens for a target AST node into token trees, and appends @@ -900,77 +935,24 @@ 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: AbsoluteTokenTreeIndex, + delimited_sequence_end: AbsoluteTokenTreeIndex, + 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 index = stream.range().start(); + let end = stream.range().one_past_end(); + TokenCursor { stream, index, delimited_sequence_end: end, depth: 0, parent: None } } /// Gets the next token and advances the cursor by one. @@ -979,86 +961,145 @@ 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.bump_single(); + } + Some(ArenaTokenTree::DelimitedStart(bounds, ..)) => { + // Skip the whole delimited sequence + index.bump_delimited(bounds); + } + 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.range().end(); + } } /// 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()) + 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.range().one_past_end()); + + 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.bump_single(); + 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) => { + // We continue into the delimited group, so we use bump_single here + self.index.bump_single(); + 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 +1156,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, 104); 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 c12f24a7eff87..18158cd087681 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -446,6 +446,7 @@ macro_rules! common_visitor_and_walkers { crate::token::LitKind, crate::tokenstream::LazyAttrTokenStream, crate::tokenstream::TokenStream, + crate::tokenarena::ArenaTokenStream, rustc_data_structures::fx::FxHashMap, rustc_span::ByteSymbol, rustc_span::ErrorGuaranteed, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 1a351cc1420f3..da18401663f6f 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/mod.rs b/compiler/rustc_ast_pretty/src/pprust/mod.rs index 19bd8fd11bf2e..ced2c822a9752 100644 --- a/compiler/rustc_ast_pretty/src/pprust/mod.rs +++ b/compiler/rustc_ast_pretty/src/pprust/mod.rs @@ -6,7 +6,7 @@ use std::borrow::Cow; use rustc_ast as ast; use rustc_ast::token::{Token, TokenKind}; -use rustc_ast::tokenstream::{TokenStream, TokenTree}; +use rustc_ast::tokenarena::{ArenaTokenStream, ArenaTokenTree}; pub use state::{ AnnNode, Comments, PpAnn, PrintState, State, print_crate, print_crate_as_interface, }; @@ -44,11 +44,11 @@ pub fn expr_to_string(e: &ast::Expr) -> String { State::new().expr_to_string(e) } -pub fn tt_to_string(tt: &TokenTree) -> String { - State::new().tt_to_string(tt) +pub fn tt_to_string(tt: &ArenaTokenTree, stream: &ArenaTokenStream) -> String { + State::new().tt_to_string(tt, stream) } -pub fn tts_to_string(tokens: &TokenStream) -> String { +pub fn tts_to_string(tokens: &ArenaTokenStream) -> String { State::new().tts_to_string(tokens) } diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 977eb0ee4592d..ed9db88fbd209 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -10,7 +10,8 @@ use std::borrow::Cow; use std::sync::Arc; use rustc_ast::attr::AttrIdGenerator; -use rustc_ast::tokenstream::{Spacing, TokenStream, TokenTree}; +use rustc_ast::tokenarena::{ArenaTokenStream, ArenaTokenTree, DelimitedData}; +use rustc_ast::tokenstream::Spacing; use rustc_ast::util::classify; use rustc_ast::util::comments::{Comment, CommentStyle}; use rustc_ast::{ @@ -324,19 +325,22 @@ fn print_crate_inner<'a>( /// Returns `true` if both token trees are identifier-like tokens that would /// merge into a single token if printed without a space between them. /// E.g. `ident` + `where` would merge into `identwhere`. -fn idents_would_merge(tt1: &TokenTree, tt2: &TokenTree) -> bool { - fn is_ident_like(tt: &TokenTree) -> bool { - matches!(tt, TokenTree::Token(tk::Token { kind: tk::Ident(..) | tk::NtIdent(..), .. }, _,)) +fn idents_would_merge(tt1: &ArenaTokenTree, tt2: &ArenaTokenTree) -> bool { + fn is_ident_like(tt: &ArenaTokenTree) -> bool { + matches!( + tt, + ArenaTokenTree::Token(tk::Token { kind: tk::Ident(..) | tk::NtIdent(..), .. }, _,) + ) } is_ident_like(tt1) && is_ident_like(tt2) } -fn space_between(tt1: &TokenTree, tt2: &TokenTree) -> bool { - use TokenTree::{Delimited as Del, Token as Tok}; +fn space_between(tt1: &ArenaTokenTree, tt2: &ArenaTokenTree) -> bool { + use ArenaTokenTree::{DelimitedStart as Del, Token as Tok}; use tk::Delimiter::{Bracket, Parenthesis}; - fn is_punct(tt: &TokenTree) -> bool { - matches!(tt, TokenTree::Token(tok, _) if tok.is_punct()) + fn is_punct(tt: &ArenaTokenTree) -> bool { + matches!(tt, ArenaTokenTree::Token(tok, _) if tok.is_punct()) } // Each match arm has one or more examples in comments. The default is to @@ -372,18 +376,23 @@ fn space_between(tt1: &TokenTree, tt2: &TokenTree) -> bool { // IDENT|`fn`|`Self`|`pub` + `(`: `f(3)`, `fn(x: u8)`, `Self()`, `pub(crate)`, // but `let (a, b) = (1, 2)` needs a space after the `let` - (Tok(tk::Token { kind: tk::Ident(sym, is_raw), span }, _), Del(_, _, Parenthesis, _)) - if !Ident::new(*sym, *span).is_reserved() - || *sym == kw::Fn - || *sym == kw::SelfUpper - || *sym == kw::Pub - || matches!(is_raw, tk::IdentIsRaw::Yes) => + ( + Tok(tk::Token { kind: tk::Ident(sym, is_raw), span }, _), + Del(_, DelimitedData { delimiter: Parenthesis, .. }), + ) if !Ident::new(*sym, *span).is_reserved() + || *sym == kw::Fn + || *sym == kw::SelfUpper + || *sym == kw::Pub + || matches!(is_raw, tk::IdentIsRaw::Yes) => { false } // `#` + `[`: `#[attr]` - (Tok(tk::Token { kind: tk::Pound, .. }, _), Del(_, _, Bracket, _)) => false, + ( + Tok(tk::Token { kind: tk::Pound, .. }, _), + Del(_, DelimitedData { delimiter: Bracket, .. }), + ) => false, _ => true, } @@ -744,9 +753,14 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere /// appropriate macro, transcribe back into the grammar we just parsed from, /// and then pretty-print the resulting AST nodes (so, e.g., we print /// expression arguments as expressions). It can be done! I think. - fn print_tt(&mut self, tt: &TokenTree, convert_dollar_crate: bool) -> Spacing { + fn print_tt( + &mut self, + tt: &ArenaTokenTree, + stream: &ArenaTokenStream, + convert_dollar_crate: bool, + ) -> Spacing { match tt { - TokenTree::Token(token, spacing) => { + ArenaTokenTree::Token(token, spacing) => { let token_str = self.token_to_string_ext(token, convert_dollar_crate); self.word(token_str); // Emit hygiene annotations for identity-bearing tokens, @@ -771,18 +785,18 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere } *spacing } - TokenTree::Delimited(dspan, spacing, delim, tts) => { + ArenaTokenTree::DelimitedStart(bounds, data) => { self.print_mac_common( None, false, None, - *delim, - Some(spacing.open), - tts, + data.delimiter, + Some(data.spacing.open), + &ArenaTokenStream::separate_delimited_inner(*bounds, stream), convert_dollar_crate, - dspan.entire(), + data.span.entire(), ); - spacing.close + data.spacing.close } } } @@ -816,10 +830,10 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere // output with simple string matching that can't handle whitespace changes. // E.g. we have seen cases where a proc macro can handle `a :: b` but not // `a::b`. See #117433 for some examples. - fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) { - let mut iter = tts.iter().peekable(); + fn print_tts(&mut self, tts: &ArenaTokenStream, convert_dollar_crate: bool) { + let mut iter = tts.iter_top_level_trees(); while let Some(tt) = iter.next() { - let spacing = self.print_tt(tt, convert_dollar_crate); + let spacing = self.print_tt(tt, tts, convert_dollar_crate); if let Some(next) = iter.peek() { if spacing == Spacing::Alone && space_between(tt, next) { self.space(); @@ -842,7 +856,7 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere ident: Option, delim: tk::Delimiter, open_spacing: Option, - tts: &TokenStream, + tts: &ArenaTokenStream, convert_dollar_crate: bool, span: Span, ) { @@ -1171,8 +1185,8 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere Self::to_string(|s| s.print_attr_item(ai, ai.path.span)) } - fn tts_to_string(&self, tokens: &TokenStream) -> String { - Self::to_string(|s| s.print_tts(tokens, false)) + fn tts_to_string(&self, stream: &ArenaTokenStream) -> String { + Self::to_string(|s| s.print_tts(stream, false)) } fn to_string(f: impl FnOnce(&mut State<'_>)) -> String { @@ -2410,9 +2424,9 @@ impl<'a> State<'a> { Self::to_string(|s| s.print_where_bound_predicate(where_bound_predicate)) } - pub(crate) fn tt_to_string(&self, tt: &TokenTree) -> String { + pub(crate) fn tt_to_string(&self, tt: &ArenaTokenTree, stream: &ArenaTokenStream) -> String { Self::to_string(|s| { - s.print_tt(tt, false); + s.print_tt(tt, stream, false); }) } diff --git a/compiler/rustc_attr_ir/src/attr.rs b/compiler/rustc_attr_ir/src/attr.rs index 6068c11590a23..51273b4ab4e44 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) } _ => None, }, diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs b/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs index 53d7044521e5a..d53224e9f6176 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg_select.rs @@ -1,5 +1,5 @@ use rustc_ast::token::Token; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{AttrStyle, NodeId, token}; use rustc_attr_ir::target::Target; use rustc_attr_ir::{AttrPath, CfgEntry}; @@ -37,18 +37,18 @@ impl CfgSelectPredicate { #[derive(Default)] pub struct CfgSelectBranches { /// All the conditional branches. - pub reachable: Vec<(CfgEntry, TokenStream, Span)>, + pub reachable: Vec<(CfgEntry, ArenaTokenStream, Span)>, /// The first wildcard `_ => { ... }` branch. - pub wildcard: Option<(Token, TokenStream, Span)>, + pub wildcard: Option<(Token, ArenaTokenStream, Span)>, /// All branches after the first wildcard, including further wildcards. /// These branches are kept for formatting. - pub unreachable: Vec<(CfgSelectPredicate, TokenStream, Span)>, + pub unreachable: Vec<(CfgSelectPredicate, ArenaTokenStream, Span)>, } impl CfgSelectBranches { /// Removes the top-most branch for which `predicate` returns `true`, /// or the wildcard if none of the reachable branches satisfied the predicate. - pub fn pop_first_match(&mut self, predicate: F) -> Option<(CfgEntry, TokenStream, Span)> + pub fn pop_first_match(&mut self, predicate: F) -> Option<(CfgEntry, ArenaTokenStream, Span)> where F: Fn(&CfgEntry) -> EvalConfigResult, { @@ -66,8 +66,8 @@ impl CfgSelectBranches { self.wildcard.take().map(|(_, tts, span)| (CfgEntry::Bool(true, span), tts, span)) } - /// Consume this value and iterate over all the `TokenStream`s that it stores. - pub fn into_iter_tts(self) -> impl Iterator { + /// Consume this value and iterate over all the `ArenaTokenStream`s that it stores. + pub fn into_iter_tts(self) -> impl Iterator { let it1 = self.reachable.into_iter(); let it2 = self.wildcard.into_iter().map(|(_, tts, span)| (CfgEntry::Bool(true, span), tts, span)); diff --git a/compiler/rustc_attr_parsing/src/parser.rs b/compiler/rustc_attr_parsing/src/parser.rs index 8efe5bf4f1f90..d5206fcfcb70a 100644 --- a/compiler/rustc_attr_parsing/src/parser.rs +++ b/compiler/rustc_attr_parsing/src/parser.rs @@ -14,7 +14,7 @@ use std::fmt::{Debug, Display}; use std::sync::atomic::{AtomicBool, Ordering}; use rustc_ast::token::{self, Delimiter, MetaVarKind}; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{ AttrArgs, Expr, ExprKind, LitKind, MetaItemLit, Path, PathSegment, StmtKind, UnOp, }; @@ -132,7 +132,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.clone(), args.dspan.entire(), psess, ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden }, @@ -163,7 +163,7 @@ impl ArgParser { Self::List( MetaItemListParser::new( - &args.tokens, + args.tokens.clone(), args.dspan.entire(), psess, should_emit, @@ -721,13 +721,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); } @@ -756,20 +756,14 @@ pub struct MetaItemListParser { } impl MetaItemListParser { - pub(crate) fn new<'sess>( - tokens: &TokenStream, + pub(crate) fn new( + tokens: ArenaTokenStream, span: Span, - psess: &'sess ParseSess, + psess: &ParseSess, should_emit: ShouldEmit, allow_expr_metavar: AllowExprMetavar, - ) -> Result> { - MetaItemListParserContext::parse( - tokens.clone(), - psess, - span, - should_emit, - allow_expr_metavar, - ) + ) -> Result> { + MetaItemListParserContext::parse(tokens, psess, span, should_emit, allow_expr_metavar) } /// Lets you pick and choose as what you want to parse each element in the list diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index 5039d27a46fb4..233148f96c672 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -1,5 +1,5 @@ use rustc_ast as ast; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{AsmMacro, token}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_errors::PResult; @@ -29,7 +29,7 @@ struct ValidatedAsmArgs { fn parse_args<'a>( ecx: &ExtCtxt<'a>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, asm_macro: AsmMacro, ) -> PResult<'a, ValidatedAsmArgs> { let args = parse_asm_args(&mut ecx.new_parser_from_tts(tts), sp, asm_macro)?; @@ -582,7 +582,7 @@ fn expand_preparsed_asm( pub(super) fn expand_asm<'cx>( ecx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { ExpandResult::Ready(match parse_args(ecx, sp, tts, AsmMacro::Asm) { Ok(args) => { @@ -611,7 +611,7 @@ pub(super) fn expand_asm<'cx>( pub(super) fn expand_naked_asm<'cx>( ecx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { ExpandResult::Ready(match parse_args(ecx, sp, tts, AsmMacro::NakedAsm) { Ok(args) => { @@ -641,7 +641,7 @@ pub(super) fn expand_naked_asm<'cx>( pub(super) fn expand_global_asm<'cx>( ecx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { ExpandResult::Ready(match parse_args(ecx, sp, tts, AsmMacro::GlobalAsm) { Ok(args) => { diff --git a/compiler/rustc_builtin_macros/src/assert.rs b/compiler/rustc_builtin_macros/src/assert.rs index 106b67d1c8ec7..dfc5fe7e34a9d 100644 --- a/compiler/rustc_builtin_macros/src/assert.rs +++ b/compiler/rustc_builtin_macros/src/assert.rs @@ -1,7 +1,8 @@ mod context; use rustc_ast::token::Delimiter; -use rustc_ast::tokenstream::{DelimSpan, TokenStream}; +use rustc_ast::tokenarena::ArenaTokenStream; +use rustc_ast::tokenstream::DelimSpan; use rustc_ast::{DelimArgs, Expr, ExprKind, MacCall, Path, PathSegment, UnOp, token}; use rustc_ast_pretty::pprust; use rustc_errors::PResult; @@ -17,7 +18,7 @@ use crate::edition_panic::use_panic_2021; pub(crate) fn expand_assert<'cx>( cx: &'cx mut ExtCtxt<'_>, span: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let Assert { cond_expr, custom_message } = match parse_assert(cx, span, tts) { Ok(assert) => assert, @@ -95,7 +96,7 @@ pub(crate) fn expand_assert<'cx>( struct Assert { cond_expr: Box, - custom_message: Option, + custom_message: Option, } // if !{ ... } { ... } else { ... } @@ -109,7 +110,7 @@ fn expr_if_not( cx.expr_if(span, cx.expr(span, ExprKind::Unary(UnOp::Not, cond)), then, els) } -fn parse_assert<'a>(cx: &ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PResult<'a, Assert> { +fn parse_assert<'a>(cx: &ExtCtxt<'a>, sp: Span, stream: ArenaTokenStream) -> PResult<'a, Assert> { let mut parser = cx.new_parser_from_tts(stream); if parser.token == token::Eof { @@ -156,7 +157,7 @@ fn parse_assert<'a>(cx: &ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PResult< Ok(Assert { cond_expr, custom_message }) } -fn parse_custom_message(parser: &mut Parser<'_>) -> Option { +fn parse_custom_message(parser: &mut Parser<'_>) -> Option { let ts = parser.parse_tokens(); if !ts.is_empty() { Some(ts) } else { None } } diff --git a/compiler/rustc_builtin_macros/src/assert/context.rs b/compiler/rustc_builtin_macros/src/assert/context.rs index 80ea2e3d877fc..542d4a07d79fc 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,7 @@ 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_iter(initial.into_iter().chain(captures)), }), })), ) diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs index 5a9988e076b0d..f2b23d37445b1 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_iter(std::iter::once(( + 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_iter(ts), }); let new_id = ecx.sess.psess.attr_id_generator.mk_attr_id(); diff --git a/compiler/rustc_builtin_macros/src/cfg.rs b/compiler/rustc_builtin_macros/src/cfg.rs index b34d928146efd..c595e072940af 100644 --- a/compiler/rustc_builtin_macros/src/cfg.rs +++ b/compiler/rustc_builtin_macros/src/cfg.rs @@ -2,7 +2,7 @@ //! a literal `true` or `false` based on whether the given cfg matches the //! current compilation environment. -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{AttrStyle, token}; use rustc_attr_ir::target::Target; use rustc_attr_ir::{AttrPath, CfgEntry}; @@ -21,7 +21,7 @@ use crate::diagnostics; pub(crate) fn expand_cfg( cx: &mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'static> { let sp = cx.with_def_site_ctxt(sp); @@ -35,7 +35,11 @@ pub(crate) fn expand_cfg( }) } -fn parse_cfg(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream) -> Result { +fn parse_cfg( + cx: &ExtCtxt<'_>, + span: Span, + tts: ArenaTokenStream, +) -> Result { let mut parser = cx.new_parser_from_tts(tts); if parser.token == token::Eof { return Err(cx.dcx().emit_err(diagnostics::RequiresCfgPattern { span })); diff --git a/compiler/rustc_builtin_macros/src/cfg_select.rs b/compiler/rustc_builtin_macros/src/cfg_select.rs index 69c3802ceafae..f2a306753e3e9 100644 --- a/compiler/rustc_builtin_macros/src/cfg_select.rs +++ b/compiler/rustc_builtin_macros/src/cfg_select.rs @@ -1,5 +1,5 @@ use rustc_ast::attr::AttrIdGenerator; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{AttrKind, Expr, SyntheticAttr, ast}; use rustc_attr_ir::CfgEntry; use rustc_attr_parsing as attr; @@ -17,7 +17,7 @@ use crate::diagnostics::CfgSelectNoMatches; struct CfgSelectResult<'cx, 'sess> { ecx: &'cx mut ExtCtxt<'sess>, site_span: Span, - selected_tts: TokenStream, + selected_tts: ArenaTokenStream, selected_span: Span, other_branches: CfgSelectBranches, cfg_entry: CfgEntry, @@ -26,7 +26,7 @@ struct CfgSelectResult<'cx, 'sess> { fn tts_to_mac_result<'cx, 'sess>( ecx: &'cx mut ExtCtxt<'sess>, site_span: Span, - tts: TokenStream, + tts: ArenaTokenStream, span: Span, ) -> Box { match ExpandResult::from_tts(ecx, tts, site_span, span, Ident::with_dummy_span(sym::cfg_select)) @@ -118,7 +118,7 @@ impl<'cx, 'sess> MacResult for CfgSelectResult<'cx, 'sess> { pub(super) fn expand_cfg_select<'cx>( ecx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { ExpandResult::Ready( match parse_cfg_select( diff --git a/compiler/rustc_builtin_macros/src/compile_error.rs b/compiler/rustc_builtin_macros/src/compile_error.rs index e2109caf2e59d..ad3d3cdcc2d05 100644 --- a/compiler/rustc_builtin_macros/src/compile_error.rs +++ b/compiler/rustc_builtin_macros/src/compile_error.rs @@ -1,6 +1,6 @@ // The compiler code necessary to support the compile_error! extension. -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; use rustc_span::Span; @@ -9,7 +9,7 @@ use crate::util::get_single_str_from_tts; pub(crate) fn expand_compile_error<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let ExpandResult::Ready(mac) = get_single_str_from_tts(cx, sp, tts, "compile_error!") else { return ExpandResult::Retry(()); diff --git a/compiler/rustc_builtin_macros/src/concat.rs b/compiler/rustc_builtin_macros/src/concat.rs index a260b3c43e8af..bab55a3653f5b 100644 --- a/compiler/rustc_builtin_macros/src/concat.rs +++ b/compiler/rustc_builtin_macros/src/concat.rs @@ -1,4 +1,4 @@ -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{ExprKind, LitKind, UnOp}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; use rustc_session::diagnostics::report_lit_error; @@ -10,7 +10,7 @@ use crate::util::get_exprs_from_tts; pub(crate) fn expand_concat( cx: &mut ExtCtxt<'_>, sp: rustc_span::Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'static> { let ExpandResult::Ready(mac) = get_exprs_from_tts(cx, tts) else { return ExpandResult::Retry(()); diff --git a/compiler/rustc_builtin_macros/src/concat_bytes.rs b/compiler/rustc_builtin_macros/src/concat_bytes.rs index 15d0f43d039f2..fbf3d71dd3e98 100644 --- a/compiler/rustc_builtin_macros/src/concat_bytes.rs +++ b/compiler/rustc_builtin_macros/src/concat_bytes.rs @@ -1,4 +1,4 @@ -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{ExprKind, LitIntType, LitKind, StrStyle, UintTy, token}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; use rustc_session::diagnostics::report_lit_error; @@ -135,7 +135,7 @@ fn handle_array_element( pub(crate) fn expand_concat_bytes( cx: &mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'static> { let ExpandResult::Ready(mac) = get_exprs_from_tts(cx, tts) else { return ExpandResult::Retry(()); diff --git a/compiler/rustc_builtin_macros/src/contracts.rs b/compiler/rustc_builtin_macros/src/contracts.rs index 20001400857a6..58cd6e192bc1e 100644 --- a/compiler/rustc_builtin_macros/src/contracts.rs +++ b/compiler/rustc_builtin_macros/src/contracts.rs @@ -1,5 +1,9 @@ use rustc_ast::token; -use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; +use rustc_ast::token::Delimiter; +use rustc_ast::tokenarena::{ + ArenaTokenStream, ArenaTokenStreamBuilder, ArenaTokenTree, DelimitedData, PerTreeOp, +}; +use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing}; use rustc_errors::ErrorGuaranteed; use rustc_expand::base::{AttrProcMacro, ExtCtxt}; use rustc_span::Span; @@ -14,9 +18,9 @@ impl AttrProcMacro for ExpandRequires { &self, ecx: &'cx mut ExtCtxt<'_>, span: Span, - annotation: TokenStream, - annotated: TokenStream, - ) -> Result { + annotation: ArenaTokenStream, + annotated: ArenaTokenStream, + ) -> Result { expand_contract_clause_tts(ecx, span, annotation, annotated, kw::ContractRequires) } } @@ -26,9 +30,9 @@ impl AttrProcMacro for ExpandEnsures { &self, ecx: &'cx mut ExtCtxt<'_>, span: Span, - annotation: TokenStream, - annotated: TokenStream, - ) -> Result { + annotation: ArenaTokenStream, + annotated: ArenaTokenStream, + ) -> Result { expand_contract_clause_tts(ecx, span, annotation, annotated, kw::ContractEnsures) } } @@ -47,20 +51,20 @@ impl AttrProcMacro for ExpandEnsures { fn expand_contract_clause( ecx: &mut ExtCtxt<'_>, attr_span: Span, - annotated: TokenStream, - inject: impl FnOnce(&mut Vec) -> Result<(), ErrorGuaranteed>, -) -> Result { - let mut new_tts = vec![]; - let mut cursor = annotated.iter(); + annotated: ArenaTokenStream, + inject: impl FnOnce(&mut ArenaTokenStreamBuilder) -> Result<(), ErrorGuaranteed>, +) -> Result { + let mut builder = ArenaTokenStreamBuilder::with_capacity(annotated.length()); + let mut cursor = annotated.iter_top_level_trees(); - let is_kw = |tt: &TokenTree, sym: Symbol| { - if let TokenTree::Token(token, _) = tt { token.is_ident_named(sym) } else { false } + let is_kw = |tt: &ArenaTokenTree, sym: Symbol| { + if let ArenaTokenTree::Token(token, _) = tt { token.is_ident_named(sym) } else { false } }; // Find the `fn` keyword to check if this is a function. if cursor .find(|tt| { - new_tts.push((*tt).clone()); + builder.push_token_tree(tt, &annotated); is_kw(tt, kw::Fn) }) .is_none() @@ -72,7 +76,7 @@ fn expand_contract_clause( } // Contracts are not yet supported on async/gen functions - if new_tts.iter().any(|tt| is_kw(tt, kw::Async) || is_kw(tt, kw::Gen)) { + if builder.tokens().iter().any(|tt| is_kw(tt, kw::Async) || is_kw(tt, kw::Gen)) { return Err(ecx.sess.dcx().span_err( attr_span, "contract annotations are not yet supported on async or gen functions", @@ -89,7 +93,11 @@ fn expand_contract_clause( }; // If `tt` is the last element. Check if it is the function body. if cursor.peek().is_none() { - if let TokenTree::Delimited(_, _, token::Delimiter::Brace, _) = tt { + if let ArenaTokenTree::DelimitedStart( + _, + DelimitedData { delimiter: token::Delimiter::Brace, .. }, + ) = tt + { break tt; } else { return Err(ecx.sess.dcx().span_err( @@ -102,7 +110,7 @@ fn expand_contract_clause( if is_kw(tt, kw::Where) { break tt; } - new_tts.push(tt.clone()); + builder.push_token_tree(tt, &annotated); }; // At this point, we've transcribed everything from the `fn` through the formal parameter list @@ -110,15 +118,21 @@ fn expand_contract_clause( // // Now inject the AST contract form. // - inject(&mut new_tts)?; + inject(&mut builder)?; // Above we injected the internal AST requires/ensures construct. Now copy over all the other // token trees. - new_tts.push(next_tt.clone()); + builder.push_token_tree(next_tt, &annotated); while let Some(tt) = cursor.next() { - new_tts.push(tt.clone()); + builder.push_token_tree(tt, &annotated); if cursor.peek().is_none() - && !matches!(tt, TokenTree::Delimited(_, _, token::Delimiter::Brace, _)) + && !matches!( + tt, + ArenaTokenTree::DelimitedStart( + _, + DelimitedData { delimiter: token::Delimiter::Brace, .. } + ) + ) { return Err(ecx.sess.dcx().span_err( attr_span, @@ -127,16 +141,16 @@ fn expand_contract_clause( } } - Ok(TokenStream::new(new_tts)) + Ok(builder.finish()) } fn expand_contract_clause_tts( ecx: &mut ExtCtxt<'_>, attr_span: Span, - annotation: TokenStream, - annotated: TokenStream, + annotation: ArenaTokenStream, + annotated: ArenaTokenStream, clause_keyword: rustc_span::Symbol, -) -> Result { +) -> Result { if annotation.is_empty() { let (name, example) = if clause_keyword == kw::ContractRequires { ("requires", "condition") @@ -153,17 +167,21 @@ fn expand_contract_clause_tts( } let feature_span = ecx.with_def_site_ctxt(attr_span); - expand_contract_clause(ecx, attr_span, annotated, |new_tts| { - new_tts.push(TokenTree::Token( + expand_contract_clause(ecx, attr_span, annotated, |builder| { + builder.push_token( token::Token::from_ast_ident(Ident::new(clause_keyword, feature_span)), Spacing::Joint, - )); - new_tts.push(TokenTree::Delimited( - DelimSpan::from_single(attr_span), - DelimSpacing::new(Spacing::JointHidden, Spacing::JointHidden), - token::Delimiter::Brace, - annotation, - )); + ); + builder.push_delimited( + |builder| { + builder.build_from_stream(&annotation, |_, _| PerTreeOp::Continue); + }, + DelimitedData { + span: DelimSpan::from_single(attr_span), + spacing: DelimSpacing::new(Spacing::JointHidden, Spacing::JointHidden), + delimiter: Delimiter::Brace, + }, + ); Ok(()) }) } diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index a041e83a646ce..ca17baf8f4012 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 SubstructureFields::*; pub(crate) use rustc_ast as ast; 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::{ AttrArgs, DelimArgs, EnumDef, Expr, GenericArg, GenericParamKind, Generics, Safety, SelfKind, VariantData, @@ -782,20 +783,19 @@ 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_iter( + [ + 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)), + ), }), span: self.span, }, diff --git a/compiler/rustc_builtin_macros/src/direct_const_arg.rs b/compiler/rustc_builtin_macros/src/direct_const_arg.rs index 6af503e9a4681..f5856ae2380f2 100644 --- a/compiler/rustc_builtin_macros/src/direct_const_arg.rs +++ b/compiler/rustc_builtin_macros/src/direct_const_arg.rs @@ -1,5 +1,5 @@ use rustc_ast::ast; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_expand::base::{self, DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; use rustc_span::Span; @@ -8,7 +8,7 @@ use crate::util::get_single_expr_from_tts; pub(crate) fn expand<'cx>( cx: &'cx mut ExtCtxt<'_>, span: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let ExpandResult::Ready(expr) = get_single_expr_from_tts(cx, span, tts, "direct_const_arg!") else { diff --git a/compiler/rustc_builtin_macros/src/edition_panic.rs b/compiler/rustc_builtin_macros/src/edition_panic.rs index ac5c43c660088..d7adb9aa07e83 100644 --- a/compiler/rustc_builtin_macros/src/edition_panic.rs +++ b/compiler/rustc_builtin_macros/src/edition_panic.rs @@ -1,5 +1,6 @@ use rustc_ast::token::Delimiter; -use rustc_ast::tokenstream::{DelimSpan, TokenStream}; +use rustc_ast::tokenarena::ArenaTokenStream; +use rustc_ast::tokenstream::DelimSpan; use rustc_ast::*; use rustc_expand::base::*; use rustc_span::edition::Edition; @@ -17,7 +18,7 @@ use rustc_span::{Span, sym}; pub(crate) fn expand_panic<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let mac = if use_panic_2021(sp) { sym::panic_2021 } else { sym::panic_2015 }; expand(mac, cx, sp, tts) @@ -30,7 +31,7 @@ pub(crate) fn expand_panic<'cx>( pub(crate) fn expand_unreachable<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let mac = if use_panic_2021(sp) { sym::unreachable_2021 } else { sym::unreachable_2015 }; expand(mac, cx, sp, tts) @@ -40,7 +41,7 @@ fn expand<'cx>( mac: rustc_span::Symbol, cx: &'cx ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let sp = cx.with_call_site_ctxt(sp); diff --git a/compiler/rustc_builtin_macros/src/eii.rs b/compiler/rustc_builtin_macros/src/eii.rs index 61b1c50180a6b..974829806ff38 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, @@ -492,21 +493,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/env.rs b/compiler/rustc_builtin_macros/src/env.rs index cced54e3cb534..36b88ed71dc2a 100644 --- a/compiler/rustc_builtin_macros/src/env.rs +++ b/compiler/rustc_builtin_macros/src/env.rs @@ -6,7 +6,7 @@ use std::env; use std::env::VarError; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{GenericArg, Mutability}; use rustc_ast_pretty::pprust; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; @@ -26,7 +26,7 @@ fn lookup_env(var: Symbol) -> Result { pub(crate) fn expand_option_env<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let ExpandResult::Ready(mac_expr) = get_single_expr_from_tts(cx, sp, tts, "option_env!") else { return ExpandResult::Retry(()); @@ -80,7 +80,7 @@ pub(crate) fn expand_option_env<'cx>( pub(crate) fn expand_env<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let ExpandResult::Ready(mac) = get_exprs_from_tts(cx, tts) else { return ExpandResult::Retry(()); diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index 745de4d129766..fc9fd36f283a3 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -1,7 +1,6 @@ use std::ops::Range; use parse::Position::ArgumentNamed; -use rustc_ast::tokenstream::TokenStream; use rustc_ast::{ Expr, ExprKind, FormatAlignment, FormatArgPosition, FormatArgPositionKind, FormatArgs, FormatArgsPiece, FormatArgument, FormatArgumentKind, FormatArguments, FormatCount, @@ -42,6 +41,7 @@ enum PositionUsedAs { Width, } use PositionUsedAs::*; +use rustc_ast::tokenarena::ArenaTokenStream; #[derive(Debug)] struct MacroInput { @@ -68,7 +68,7 @@ struct MacroInput { /// ```text /// Ok((fmtstr, parsed arguments)) /// ``` -fn parse_args<'a>(ecx: &ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<'a, MacroInput> { +fn parse_args<'a>(ecx: &ExtCtxt<'a>, sp: Span, tts: ArenaTokenStream) -> PResult<'a, MacroInput> { let mut p = ecx.new_parser_from_tts(tts); // parse the format string @@ -1127,7 +1127,7 @@ fn report_invalid_references( fn expand_format_args_impl<'cx>( ecx: &'cx mut ExtCtxt<'_>, mut sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, nl: bool, ) -> MacroExpanderResult<'cx> { sp = ecx.with_def_site_ctxt(sp); @@ -1153,7 +1153,7 @@ fn expand_format_args_impl<'cx>( pub(crate) fn expand_format_args<'cx>( ecx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { expand_format_args_impl(ecx, sp, tts, false) } @@ -1161,7 +1161,7 @@ pub(crate) fn expand_format_args<'cx>( pub(crate) fn expand_format_args_nl<'cx>( ecx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { expand_format_args_impl(ecx, sp, tts, true) } diff --git a/compiler/rustc_builtin_macros/src/iter.rs b/compiler/rustc_builtin_macros/src/iter.rs index 86bf347cd9848..067e0f5ed80f6 100644 --- a/compiler/rustc_builtin_macros/src/iter.rs +++ b/compiler/rustc_builtin_macros/src/iter.rs @@ -1,4 +1,4 @@ -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{CoroutineKind, CoroutineMarker, Expr, ast, token}; use rustc_errors::PResult; use rustc_expand::base::{self, DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; @@ -7,7 +7,7 @@ use rustc_span::Span; pub(crate) fn expand<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let closure = match parse_closure(cx, sp, tts) { Ok(parsed) => parsed, @@ -22,7 +22,7 @@ pub(crate) fn expand<'cx>( fn parse_closure<'a>( cx: &mut ExtCtxt<'a>, span: Span, - stream: TokenStream, + stream: ArenaTokenStream, ) -> PResult<'a, Box> { let mut closure_parser = cx.new_parser_from_tts(stream); diff --git a/compiler/rustc_builtin_macros/src/log_syntax.rs b/compiler/rustc_builtin_macros/src/log_syntax.rs index 205f21ae7c9d3..b6ce04ae320b1 100644 --- a/compiler/rustc_builtin_macros/src/log_syntax.rs +++ b/compiler/rustc_builtin_macros/src/log_syntax.rs @@ -1,11 +1,11 @@ -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast_pretty::pprust; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; pub(crate) fn expand_log_syntax<'cx>( _cx: &'cx mut ExtCtxt<'_>, sp: rustc_span::Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { println!("{}", pprust::tts_to_string(&tts)); diff --git a/compiler/rustc_builtin_macros/src/offload.rs b/compiler/rustc_builtin_macros/src/offload.rs index 4111843b0c9d8..48f95ee7e6e13 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_iter(std::iter::once(( + Token::new(TokenKind::Ident(sym::never, false.into()), span), + Spacing::Joint, + ))), }; let inline_item = ast::AttrItem { diff --git a/compiler/rustc_builtin_macros/src/pattern_type.rs b/compiler/rustc_builtin_macros/src/pattern_type.rs index 215baf099416b..7f9302d9235b2 100644 --- a/compiler/rustc_builtin_macros/src/pattern_type.rs +++ b/compiler/rustc_builtin_macros/src/pattern_type.rs @@ -1,4 +1,4 @@ -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{AnonConst, DUMMY_NODE_ID, Ty, TyPat, TyPatKind, ast, token}; use rustc_errors::PResult; use rustc_expand::base::{self, DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; @@ -9,7 +9,7 @@ use rustc_span::Span; pub(crate) fn expand<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let (ty, pat) = match parse_pat_ty(cx, tts) { Ok(parsed) => parsed, @@ -23,7 +23,7 @@ pub(crate) fn expand<'cx>( fn parse_pat_ty<'a>( cx: &mut ExtCtxt<'a>, - stream: TokenStream, + stream: ArenaTokenStream, ) -> PResult<'a, (Box, Box)> { let mut parser = cx.new_parser_from_tts(stream); diff --git a/compiler/rustc_builtin_macros/src/source_util.rs b/compiler/rustc_builtin_macros/src/source_util.rs index 37b2f49c3596d..8ca26def50541 100644 --- a/compiler/rustc_builtin_macros/src/source_util.rs +++ b/compiler/rustc_builtin_macros/src/source_util.rs @@ -5,7 +5,7 @@ use std::rc::Rc; use std::sync::Arc; use rustc_ast as ast; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{join_path_idents, token}; use rustc_ast_pretty::pprust; use rustc_expand::base::{ @@ -30,10 +30,10 @@ use crate::util::{ pub(crate) fn expand_line( cx: &mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'static> { let sp = cx.with_def_site_ctxt(sp); - check_zero_tts(cx, sp, tts, "line!"); + check_zero_tts(cx, sp, &tts, "line!"); let topmost = cx.expansion_cause().unwrap_or(sp); let loc = cx.source_map().lookup_char_pos(topmost.lo()); @@ -45,10 +45,10 @@ pub(crate) fn expand_line( pub(crate) fn expand_column( cx: &mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'static> { let sp = cx.with_def_site_ctxt(sp); - check_zero_tts(cx, sp, tts, "column!"); + check_zero_tts(cx, sp, &tts, "column!"); let topmost = cx.expansion_cause().unwrap_or(sp); let loc = cx.source_map().lookup_char_pos(topmost.lo()); @@ -60,10 +60,10 @@ pub(crate) fn expand_column( pub(crate) fn expand_file( cx: &mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'static> { let sp = cx.with_def_site_ctxt(sp); - check_zero_tts(cx, sp, tts, "file!"); + check_zero_tts(cx, sp, &tts, "file!"); let topmost = cx.expansion_cause().unwrap_or(sp); let loc = cx.source_map().lookup_char_pos(topmost.lo()); @@ -79,7 +79,7 @@ pub(crate) fn expand_file( pub(crate) fn expand_stringify( cx: &mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'static> { let sp = cx.with_def_site_ctxt(sp); let s = pprust::tts_to_string(&tts); @@ -90,10 +90,10 @@ pub(crate) fn expand_stringify( pub(crate) fn expand_mod( cx: &mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'static> { let sp = cx.with_def_site_ctxt(sp); - check_zero_tts(cx, sp, tts, "module_path!"); + check_zero_tts(cx, sp, &tts, "module_path!"); let mod_path = &cx.current_expansion.module.mod_path; let string = join_path_idents(mod_path); @@ -106,7 +106,7 @@ pub(crate) fn expand_mod( pub(crate) fn expand_include<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let sp = cx.with_def_site_ctxt(sp); let ExpandResult::Ready(mac) = get_single_str_from_tts(cx, sp, tts, "include!") else { @@ -204,7 +204,7 @@ pub(crate) fn expand_include<'cx>( pub(crate) fn expand_include_str( cx: &mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'static> { let sp = cx.with_def_site_ctxt(sp); let ExpandResult::Ready(mac) = get_single_str_spanned_from_tts(cx, sp, tts, "include_str!") @@ -238,7 +238,7 @@ pub(crate) fn expand_include_str( pub(crate) fn expand_include_bytes( cx: &mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'static> { let sp = cx.with_def_site_ctxt(sp); let ExpandResult::Ready(mac) = get_single_str_spanned_from_tts(cx, sp, tts, "include_bytes!") diff --git a/compiler/rustc_builtin_macros/src/test_binder_constraints.rs b/compiler/rustc_builtin_macros/src/test_binder_constraints.rs index 0c7482672df46..e46b13caffe15 100644 --- a/compiler/rustc_builtin_macros/src/test_binder_constraints.rs +++ b/compiler/rustc_builtin_macros/src/test_binder_constraints.rs @@ -1,4 +1,4 @@ -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{AttrVec, VisibilityKind, ast, token}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; use rustc_span::Span; @@ -9,7 +9,7 @@ use crate::diagnostics; pub(crate) fn expand<'cx>( cx: &'cx mut ExtCtxt<'_>, span: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let name = "test_binder_constraints!"; let mut p = cx.new_parser_from_tts(tts); diff --git a/compiler/rustc_builtin_macros/src/trace_macros.rs b/compiler/rustc_builtin_macros/src/trace_macros.rs index 88837e01a9407..c99516742b28e 100644 --- a/compiler/rustc_builtin_macros/src/trace_macros.rs +++ b/compiler/rustc_builtin_macros/src/trace_macros.rs @@ -1,4 +1,4 @@ -use rustc_ast::tokenstream::{TokenStream, TokenTree}; +use rustc_ast::tokenarena::{ArenaTokenStream, ArenaTokenTree}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; use rustc_span::{Span, kw}; @@ -7,13 +7,13 @@ use crate::diagnostics; pub(crate) fn expand_trace_macros( cx: &mut ExtCtxt<'_>, sp: Span, - tt: TokenStream, + tt: ArenaTokenStream, ) -> MacroExpanderResult<'static> { - let mut iter = tt.iter(); + let mut iter = tt.iter_top_level_trees(); let mut err = false; let value = match iter.next() { - Some(TokenTree::Token(token, _)) if token.is_keyword(kw::True) => true, - Some(TokenTree::Token(token, _)) if token.is_keyword(kw::False) => false, + Some(ArenaTokenTree::Token(token, _)) if token.is_keyword(kw::True) => true, + Some(ArenaTokenTree::Token(token, _)) if token.is_keyword(kw::False) => false, _ => { err = true; false diff --git a/compiler/rustc_builtin_macros/src/util.rs b/compiler/rustc_builtin_macros/src/util.rs index 80fa3e3b8ac8d..5d6a183245b5e 100644 --- a/compiler/rustc_builtin_macros/src/util.rs +++ b/compiler/rustc_builtin_macros/src/util.rs @@ -1,4 +1,4 @@ -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{self as ast, AttrStyle, Attribute, MetaItem, attr, token}; use rustc_attr_parsing::{AttributeTemplate, validate_attr}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed}; @@ -147,7 +147,7 @@ pub(crate) fn expr_to_string( /// returns even when `tts` is non-empty, macros that *need* to stop /// compilation should call `cx.diagnostic().abort_if_errors()` /// (this should be done as rarely as possible). -pub(crate) fn check_zero_tts(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream, name: &str) { +pub(crate) fn check_zero_tts(cx: &ExtCtxt<'_>, span: Span, tts: &ArenaTokenStream, name: &str) { if !tts.is_empty() { cx.dcx().emit_err(diagnostics::TakesNoArguments { span, name }); } @@ -170,7 +170,7 @@ pub(crate) fn parse_expr(p: &mut parser::Parser<'_>) -> Result, E pub(crate) fn get_single_str_from_tts( cx: &mut ExtCtxt<'_>, span: Span, - tts: TokenStream, + tts: ArenaTokenStream, name: &str, ) -> ExpandResult, ()> { get_single_str_spanned_from_tts(cx, span, tts, name).map(|res| res.map(|(s, _)| s)) @@ -179,7 +179,7 @@ pub(crate) fn get_single_str_from_tts( pub(crate) fn get_single_str_spanned_from_tts( cx: &mut ExtCtxt<'_>, span: Span, - tts: TokenStream, + tts: ArenaTokenStream, name: &str, ) -> ExpandResult, ()> { let ExpandResult::Ready(ret) = get_single_expr_from_tts(cx, span, tts, name) else { @@ -203,7 +203,7 @@ pub(crate) fn get_single_str_spanned_from_tts( pub(crate) fn get_single_expr_from_tts( cx: &mut ExtCtxt<'_>, span: Span, - tts: TokenStream, + tts: ArenaTokenStream, name: &str, ) -> ExpandResult, ErrorGuaranteed>, ()> { let mut p = cx.new_parser_from_tts(tts); @@ -227,7 +227,7 @@ pub(crate) fn get_single_expr_from_tts( /// On error, emit it, and return `Err`. pub(crate) fn get_exprs_from_tts( cx: &mut ExtCtxt<'_>, - tts: TokenStream, + tts: ArenaTokenStream, ) -> ExpandResult>, ErrorGuaranteed>, ()> { let mut p = cx.new_parser_from_tts(tts); let mut es = Vec::new(); diff --git a/compiler/rustc_builtin_macros/src/view_type.rs b/compiler/rustc_builtin_macros/src/view_type.rs index 090603f4f1253..6818aca1a65ac 100644 --- a/compiler/rustc_builtin_macros/src/view_type.rs +++ b/compiler/rustc_builtin_macros/src/view_type.rs @@ -1,5 +1,5 @@ use rustc_ast::token::TokenKind; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::{Ty, ast}; use rustc_errors::PResult; use rustc_expand::base::{self, DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; @@ -10,7 +10,7 @@ use thin_vec::ThinVec; pub(crate) fn expand<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, - tts: TokenStream, + tts: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { let (ty, pat) = match parse_view_ty(cx, tts) { Ok(parsed) => parsed, @@ -24,7 +24,7 @@ pub(crate) fn expand<'cx>( fn parse_view_ty<'a>( cx: &mut ExtCtxt<'a>, - stream: TokenStream, + stream: ArenaTokenStream, ) -> PResult<'a, (Box, ThinVec)> { let mut parser = cx.new_parser_from_tts(stream); diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index fda75319b087b..00b3f0090e67d 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -6,7 +6,7 @@ use std::rc::Rc; use std::sync::Arc; use rustc_ast::attr::MarkedAttrs; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::visit::{AssocCtxt, Visitor}; use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind, Safety}; use rustc_attr_ir::{self as attrs, CfgEntry, Deprecation, Stability, find_attr}; @@ -117,16 +117,16 @@ impl Annotatable { } /// Converts the `Annotatable` to a token stream, e.g. to hand to a proc macro. - pub fn to_tokens(&self) -> TokenStream { + pub fn to_tokens(&self) -> ArenaTokenStream { match self { - Annotatable::Item(node) => TokenStream::from_ast(node), - Annotatable::AssocItem(node, _) => TokenStream::from_ast(node), - Annotatable::ForeignItem(node) => TokenStream::from_ast(node), + Annotatable::Item(node) => ArenaTokenStream::from_ast(node), + Annotatable::AssocItem(node, _) => ArenaTokenStream::from_ast(node), + Annotatable::ForeignItem(node) => ArenaTokenStream::from_ast(node), Annotatable::Stmt(node) => { assert!(!matches!(node.kind, ast::StmtKind::Empty)); - TokenStream::from_ast(node) + ArenaTokenStream::from_ast(node) } - Annotatable::Expr(node) => TokenStream::from_ast(node), + Annotatable::Expr(node) => ArenaTokenStream::from_ast(node), Annotatable::Arm(..) | Annotatable::ExprField(..) | Annotatable::PatField(..) @@ -269,7 +269,7 @@ impl<'cx> MacroExpanderResult<'cx> { /// The `TokenStream` is forwarded without any expansion. pub fn from_tts( cx: &'cx mut ExtCtxt<'_>, - tts: TokenStream, + tts: ArenaTokenStream, site_span: Span, arm_span: Span, macro_ident: Ident, @@ -315,20 +315,20 @@ pub trait BangProcMacro { &self, ecx: &'cx mut ExtCtxt<'_>, span: Span, - ts: TokenStream, - ) -> Result; + ts: ArenaTokenStream, + ) -> Result; } impl BangProcMacro for F where - F: Fn(&mut ExtCtxt<'_>, Span, TokenStream) -> Result, + F: Fn(&mut ExtCtxt<'_>, Span, ArenaTokenStream) -> Result, { fn expand<'cx>( &self, ecx: &'cx mut ExtCtxt<'_>, span: Span, - ts: TokenStream, - ) -> Result { + ts: ArenaTokenStream, + ) -> Result { // FIXME setup implicit context in TLS before calling self. self(ecx, span, ts) } @@ -339,9 +339,9 @@ pub trait AttrProcMacro { &self, ecx: &'cx mut ExtCtxt<'_>, span: Span, - annotation: TokenStream, - annotated: TokenStream, - ) -> Result; + annotation: ArenaTokenStream, + annotated: ArenaTokenStream, + ) -> Result; // Default implementation for safe attributes; override if the attribute can be unsafe. fn expand_with_safety<'cx>( @@ -349,9 +349,9 @@ pub trait AttrProcMacro { ecx: &'cx mut ExtCtxt<'_>, safety: Safety, span: Span, - annotation: TokenStream, - annotated: TokenStream, - ) -> Result { + annotation: ArenaTokenStream, + annotated: ArenaTokenStream, + ) -> Result { if let Safety::Unsafe(span) = safety { ecx.dcx().span_err(span, "unnecessary `unsafe` on safe attribute"); } @@ -361,15 +361,15 @@ pub trait AttrProcMacro { impl AttrProcMacro for F where - F: Fn(TokenStream, TokenStream) -> TokenStream, + F: Fn(ArenaTokenStream, ArenaTokenStream) -> ArenaTokenStream, { fn expand<'cx>( &self, _ecx: &'cx mut ExtCtxt<'_>, _span: Span, - annotation: TokenStream, - annotated: TokenStream, - ) -> Result { + annotation: ArenaTokenStream, + annotated: ArenaTokenStream, + ) -> Result { // FIXME setup implicit context in TLS before calling self. Ok(self(annotation, annotated)) } @@ -381,24 +381,24 @@ pub trait TTMacroExpander: Any { &'a self, ecx: &'cx mut ExtCtxt<'_>, span: Span, - input: TokenStream, + input: ArenaTokenStream, ) -> MacroExpanderResult<'cx>; } pub type MacroExpanderResult<'cx> = ExpandResult, ()>; pub type MacroExpanderFn = - for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> MacroExpanderResult<'cx>; + for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, ArenaTokenStream) -> MacroExpanderResult<'cx>; impl TTMacroExpander for F where - F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> MacroExpanderResult<'cx>, + F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, ArenaTokenStream) -> MacroExpanderResult<'cx>, { fn expand<'cx, 'a: 'cx>( &'a self, ecx: &'cx mut ExtCtxt<'_>, span: Span, - input: TokenStream, + input: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { self(ecx, span, input) } @@ -934,8 +934,8 @@ impl SyntaxExtension { fn expand( ecx: &mut ExtCtxt<'_>, span: Span, - _ts: TokenStream, - ) -> Result { + _ts: ArenaTokenStream, + ) -> Result { Err(ecx.dcx().span_delayed_bug(span, "expanded a dummy bang macro")) } SyntaxExtension::default(SyntaxExtensionKind::Bang(Arc::new(expand)), edition) @@ -1257,7 +1257,7 @@ impl<'a> ExtCtxt<'a> { pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> { expand::MacroExpander::new(self, true) } - pub fn new_parser_from_tts(&self, stream: TokenStream) -> Parser<'a> { + pub fn new_parser_from_tts(&self, stream: ArenaTokenStream) -> Parser<'a> { Parser::new(&self.sess.psess, stream, MACRO_ARGUMENTS) } pub fn source_map(&self) -> &'a SourceMap { diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index 0e9d9ec5e8b7e..b574959b239fd 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..1b4eddf40c6c2 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use std::{iter, mem, slice}; use rustc_ast::mut_visit::*; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_ast::visit::{AssocCtxt, Visitor, VisitorResult, try_visit, walk_list}; use rustc_ast::{ self as ast, AssocItemKind, AstNodeWrapper, AttrArgs, AttrKind, AttrStyle, AttrVec, @@ -1052,7 +1052,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { fn parse_ast_fragment( &mut self, - toks: TokenStream, + toks: ArenaTokenStream, kind: AstFragmentKind, path: &ast::Path, span: Span, diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 0e79dadb3503e..d02a2707321a9 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -1,7 +1,8 @@ use std::borrow::Cow; use rustc_ast::token::{self, Token}; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::{ArenaTokenStream, ArenaTokenStreamBuilder, ArenaTokenTree, PerTreeOp}; +use rustc_ast::tokenstream::Spacing; use rustc_attr_ir::diagnostic::{CustomDiagnostic, Directive, FormatArgs}; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{Applicability, Diag, DiagCtxtHandle, DiagMessage, pluralize}; @@ -22,7 +23,7 @@ use crate::mbe::macro_rules::{ pub(super) enum FailedMacro<'a> { Func, - Attr(&'a TokenStream), + Attr(&'a ArenaTokenStream), Derive, } @@ -32,7 +33,7 @@ pub(super) fn failed_to_match_macro( def_span: Span, name: Ident, args: FailedMacro<'_>, - body: &TokenStream, + body: &ArenaTokenStream, rules: &[MacroRule], on_unmatched_args: Option<&Directive>, ) -> (Span, ErrorGuaranteed) { @@ -48,7 +49,7 @@ pub(super) fn failed_to_match_macro( let mut tracker = CollectTrackerAndEmitter::new(name, psess.dcx(), sp); let try_success_result = match args { - FailedMacro::Func => try_match_macro(psess, body, rules, &mut tracker), + FailedMacro::Func => try_match_macro(psess, &body, rules, &mut tracker), FailedMacro::Attr(attr_args) => { try_match_macro_attr(psess, attr_args, body, rules, &mut tracker) } @@ -117,7 +118,7 @@ pub(super) fn failed_to_match_macro( // Check whether there's a missing comma in this macro call, like `println!("{}" a);` if let FailedMacro::Func = args - && let Some((body, comma_span)) = body.add_comma() + && let Some((body, comma_span)) = add_comma(body) { for rule in rules { let MacroRule::Func { lhs, .. } = rule else { continue }; @@ -144,6 +145,45 @@ pub(super) fn failed_to_match_macro( (sp, guar) } +/// Given an `ArenaTokenStream` with a `Stream` of only two arguments, return a new `ArenaTokenStream` +/// separating the two arguments with a comma for diagnostic suggestions. +fn add_comma(stream: &ArenaTokenStream) -> Option<(ArenaTokenStream, Span)> { + // Used to suggest if a user writes `foo!(a b);` + let mut suggestion = None; + let mut iter = stream.iter_top_level_trees().enumerate().peekable(); + while let Some((pos, ts)) = iter.next() { + if let Some((_, next)) = iter.peek() { + let sp = match (&ts, &next) { + (_, ArenaTokenTree::Token(Token { kind: token::Comma, .. }, _)) => continue, + ( + ArenaTokenTree::Token(token_left, Spacing::Alone), + ArenaTokenTree::Token(token_right, _), + ) if (token_left.is_non_reserved_ident() || token_left.is_lit()) + && (token_right.is_non_reserved_ident() || token_right.is_lit()) => + { + token_left.span + } + (ArenaTokenTree::DelimitedStart(_, data), _) => data.span.entire(), + _ => continue, + }; + let sp = sp.shrink_to_hi(); + let comma = Token::new(token::Comma, sp); + suggestion = Some((pos, comma, sp)); + } + } + if let Some((pos, token, sp)) = suggestion { + let mut builder = ArenaTokenStreamBuilder::with_capacity(stream.length() + 1); + builder.build_from_stream(stream, |builder, _| { + if builder.length() == pos + 1 { + builder.push_token(token, Spacing::Alone); + } + PerTreeOp::Continue + }); + return Some((builder.finish(), sp)); + } + None +} + /// The tracker used for the slow error path that collects useful info for diagnostics. struct CollectTrackerAndEmitter<'dcx, 'matcher> { macro_name: Ident, diff --git a/compiler/rustc_expand/src/mbe/macro_parser.rs b/compiler/rustc_expand/src/mbe/macro_parser.rs index 3e94e0ca34773..1b7cbcd4958b1 100644 --- a/compiler/rustc_expand/src/mbe/macro_parser.rs +++ b/compiler/rustc_expand/src/mbe/macro_parser.rs @@ -78,6 +78,7 @@ use std::rc::Rc; pub(crate) use NamedMatch::*; pub(crate) use ParseResult::*; use rustc_ast::token::{self, DocComment, NonterminalKind, Token, TokenKind}; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Diag, ErrorGuaranteed}; use rustc_parse::parser::{ParseNtResult, Parser, token_descr}; @@ -380,14 +381,14 @@ pub(super) fn count_metavar_decls(matcher: &[TokenTree]) -> usize { #[derive(Debug, Clone)] pub(crate) enum NamedMatch { MatchedSeq(Vec), - MatchedSingle(ParseNtResult), + MatchedSingle(ParseNtResult, ArenaTokenStream), } impl NamedMatch { pub(super) fn is_repeatable(&self) -> bool { match self { NamedMatch::MatchedSeq(_) => true, - NamedMatch::MatchedSingle(_) => false, + NamedMatch::MatchedSingle(_, _) => false, } } } @@ -616,7 +617,11 @@ impl TtParser { Err(err) => return Some(self.nt_parsing_error(matcher_loc, err)), Ok(nt) => nt, }; - mp.push_match(next_metavar, seq_depth, MatchedSingle(nt)); + mp.push_match( + next_metavar, + seq_depth, + MatchedSingle(nt, parser.token_stream().clone()), + ); mp.idx += 1; self.cur_mps.push(mp); diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 2212724c68bc1..01383a1acebce 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -1,14 +1,18 @@ use std::borrow::Cow; use std::collections::hash_map::Entry; use std::sync::Arc; -use std::{mem, slice}; +use std::{cmp, mem, slice}; 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::{self as ast, DUMMY_NODE_ID, NodeId, Safety}; +use rustc_ast::tokenarena::{ + ArenaTokenStream, ArenaTokenStreamBuilder, ArenaTokenTree, DelimitedBounds, DelimitedData, + PerTreeOp, +}; +use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing}; +use rustc_ast::{self as ast, AttrStyle, DUMMY_NODE_ID, NodeId, Safety}; use rustc_ast_pretty::pprust; use rustc_attr_ir::diagnostic::Directive; use rustc_attr_ir::{self as attrs, find_attr}; @@ -122,7 +126,7 @@ impl<'a, 'b> ParserAnyMacro<'a, 'b> { #[instrument(skip(cx, tts, bindings, matched_rule_bindings))] pub(crate) fn from_tts<'cx>( cx: &'cx mut ExtCtxt<'a>, - tts: TokenStream, + tts: ArenaTokenStream, site_span: Span, arm_span: Span, is_local: bool, @@ -231,8 +235,8 @@ impl MacroRulesMacroExpander { &self, cx: &mut ExtCtxt<'_>, sp: Span, - body: &TokenStream, - ) -> Result { + body: &ArenaTokenStream, + ) -> Result { // This is similar to `expand_macro`, but they have very different signatures, and will // diverge further once derives support arguments. let name = self.name; @@ -292,7 +296,7 @@ impl TTMacroExpander for MacroRulesMacroExpander { &'a self, cx: &'cx mut ExtCtxt<'_>, sp: Span, - input: TokenStream, + input: ArenaTokenStream, ) -> MacroExpanderResult<'cx> { ExpandResult::Ready(expand_macro( cx, @@ -313,9 +317,9 @@ impl AttrProcMacro for MacroRulesMacroExpander { &self, _cx: &mut ExtCtxt<'_>, _sp: Span, - _args: TokenStream, - _body: TokenStream, - ) -> Result { + _args: ArenaTokenStream, + _body: ArenaTokenStream, + ) -> Result { unreachable!("`expand` called on `MacroRulesMacroExpander`, expected `expand_with_safety`") } @@ -324,9 +328,9 @@ impl AttrProcMacro for MacroRulesMacroExpander { cx: &mut ExtCtxt<'_>, safety: Safety, sp: Span, - args: TokenStream, - body: TokenStream, - ) -> Result { + args: ArenaTokenStream, + body: ArenaTokenStream, + ) -> Result { expand_macro_attr( cx, sp, @@ -350,8 +354,8 @@ impl BangProcMacro for DummyBang { &self, _: &'cx mut ExtCtxt<'_>, _: Span, - _: TokenStream, - ) -> Result { + _: ArenaTokenStream, + ) -> Result { Err(self.0) } } @@ -435,7 +439,7 @@ fn expand_macro<'cx, 'a: 'cx>( node_id: NodeId, name: Ident, transparency: Transparency, - arg: TokenStream, + arg: ArenaTokenStream, rules: &'a [MacroRule], on_unmatched_args: Option<&Directive>, ) -> Box { @@ -514,11 +518,11 @@ fn expand_macro_attr( name: Ident, transparency: Transparency, safety: Safety, - args: TokenStream, - body: TokenStream, + args: ArenaTokenStream, + body: ArenaTokenStream, rules: &[MacroRule], on_unmatched_args: Option<&Directive>, -) -> Result { +) -> Result { let psess = &cx.sess.psess; // Macros defined in the current crate have a real node id, // whereas macros from an external crate have a dummy id. @@ -606,7 +610,7 @@ pub(super) enum CanRetry { #[instrument(level = "debug", skip(psess, arg, rules, track), fields(tracking = %T::description()))] pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>( psess: &ParseSess, - arg: &TokenStream, + arg: &ArenaTokenStream, rules: &'matcher [MacroRule], track: &mut T, ) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> { @@ -685,8 +689,8 @@ pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>( #[instrument(level = "debug", skip(psess, attr_args, attr_body, rules, track), fields(tracking = %T::description()))] pub(super) fn try_match_macro_attr<'matcher, T: Tracker<'matcher>>( psess: &ParseSess, - attr_args: &TokenStream, - attr_body: &TokenStream, + attr_args: &ArenaTokenStream, + attr_body: &ArenaTokenStream, rules: &'matcher [MacroRule], track: &mut T, ) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> { @@ -741,7 +745,7 @@ pub(super) fn try_match_macro_attr<'matcher, T: Tracker<'matcher>>( #[instrument(level = "debug", skip(psess, body, rules, track), fields(tracking = %T::description()))] pub(super) fn try_match_macro_derive<'matcher, T: Tracker<'matcher>>( psess: &ParseSess, - body: &TokenStream, + body: &ArenaTokenStream, rules: &'matcher [MacroRule], track: &mut T, ) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> { @@ -819,9 +823,18 @@ 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, + 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); @@ -841,9 +854,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") { @@ -870,7 +884,15 @@ pub fn compile_declarative_macro( (None, false) }; let lhs_tt = p.parse_token_tree(); - let lhs_tt = parse_one_tt(lhs_tt, RulePart::Pattern, sess, node_id, features, edition); + let lhs_tt = parse_one_tt( + lhs_tt, + p.token_stream(), + 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)) { return dummy_syn_ext(e.emit()); @@ -879,7 +901,8 @@ pub fn compile_declarative_macro( return dummy_syn_ext(guar); } let rhs = p.parse_token_tree(); - let rhs = parse_one_tt(rhs, RulePart::Body, sess, node_id, features, edition); + let rhs = + parse_one_tt(rhs, p.token_stream(), 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)); let lhs_span = lhs_tt.span(); @@ -958,25 +981,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)) } } } @@ -1862,9 +1892,84 @@ fn is_defined_in_current_crate(node_id: NodeId) -> bool { pub(super) fn parser_from_cx( psess: &ParseSess, - mut tts: TokenStream, + tts: ArenaTokenStream, recovery: Recovery, ) -> Parser<'_> { - tts.desugar_doc_comments(); + let tts = desugar_doc_comments(tts); Parser::new(psess, tts, rustc_parse::MACRO_ARGUMENTS).recovery(recovery) } + +/// Desugar doc comments like `/// foo` in the stream into `#[doc = +/// r"foo"]`. +fn desugar_doc_comments(stream: ArenaTokenStream) -> ArenaTokenStream { + // Fast path to avoid modifications + let mut doc_comment_found = false; + for tree in stream.iter_all_trees() { + if let ArenaTokenTree::Token(Token { kind: token::DocComment(..), .. }, ..) = tree { + doc_comment_found = true; + break; + } + } + if !doc_comment_found { + return stream; + } + + let mut builder = ArenaTokenStreamBuilder::with_capacity(stream.length()); + builder.build_from_stream(&stream, |builder, tree| { + if let ArenaTokenTree::Token( + Token { kind: token::DocComment(_, attr_style, data), span }, + _, + ) = tree + { + let span = *span; + // Searches for the occurrences of `"#*` and returns the minimum number of `#`s + // required to wrap the text. E.g. + // - `abc d` is wrapped as `r"abc d"` (num_of_hashes = 0) + // - `abc "d"` is wrapped as `r#"abc "d""#` (num_of_hashes = 1) + // - `abc "##d##"` is wrapped as `r###"abc ##"d"##"###` (num_of_hashes = 3) + let mut num_of_hashes = 0; + let mut count = 0; + for ch in data.as_str().chars() { + count = match ch { + '"' => 1, + '#' if count > 0 => count + 1, + _ => 0, + }; + num_of_hashes = cmp::max(num_of_hashes, count); + } + + if *attr_style == AttrStyle::Inner { + builder.push_token(Token::new(token::Pound, span), Spacing::Joint); + builder.push_token(Token::new(token::Bang, span), Spacing::JointHidden); + } else { + builder.push_token(Token::new(token::Pound, span), Spacing::JointHidden); + } + + // `/// foo` becomes `[doc = r"foo"]`. + let delim_span = DelimSpan::from_single(span); + builder.push_delimited( + |builder| { + builder.push_token_alone(Token::new( + token::Ident(sym::doc, token::IdentIsRaw::No), + span, + )); + builder.push_token_alone(Token::new(token::Eq, span)); + builder.push_token_alone(Token::new( + TokenKind::lit(token::StrRaw(num_of_hashes), *data, None), + span, + )); + }, + DelimitedData { + span: delim_span, + delimiter: Delimiter::Bracket, + spacing: DelimSpacing::new(Spacing::JointHidden, Spacing::Alone), + }, + ); + + PerTreeOp::Skip + } else { + PerTreeOp::Continue + } + }); + builder.finish() +} diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs index a02b84204cb39..a3e0fe9c3f67c 100644 --- a/compiler/rustc_expand/src/mbe/metavar_expr.rs +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -1,5 +1,5 @@ use rustc_ast::token::{self, Delimiter, IdentIsRaw, Lit, Token, TokenKind}; -use rustc_ast::tokenstream::{TokenStream, TokenStreamIter, TokenTree}; +use rustc_ast::tokenarena::{ArenaTokenTree, ArenaTokenTreeIter, DelimitedData}; use rustc_ast::{LitIntType, LitKind}; use rustc_ast_pretty::pprust; use rustc_errors::{Applicability, PResult}; @@ -36,18 +36,21 @@ pub(crate) enum MetaVarExpr { impl MetaVarExpr { /// Attempt to parse a meta-variable expression from a token stream. pub(crate) fn parse<'psess>( - input: &TokenStream, + mut iter: ArenaTokenTreeIter<'_>, outer_span: Span, psess: &'psess ParseSess, ) -> PResult<'psess, MetaVarExpr> { - let mut iter = input.iter(); let ident = parse_ident(&mut iter, psess, outer_span)?; let next = iter.next(); - let Some(TokenTree::Delimited(.., Delimiter::Parenthesis, args)) = next else { + let Some(ArenaTokenTree::DelimitedStart( + bounds, + DelimitedData { delimiter: Delimiter::Parenthesis, .. }, + )) = next + else { // No `()`; wrong or no delimiters. Point at a problematic span or a place to // add parens if it makes sense. let (unexpected_span, insert_span) = match next { - Some(TokenTree::Delimited(..)) => (None, None), + Some(ArenaTokenTree::DelimitedStart(..)) => (None, None), Some(tt) => (Some(tt.span()), None), None => (None, Some(ident.span.shrink_to_hi())), }; @@ -61,7 +64,7 @@ impl MetaVarExpr { // Ensure there are no trailing tokens in the braces, e.g. `${foo() extra}` if iter.peek().is_some() { - let span = iter_span(&iter).expect("checked is_some above"); + let span = iter_span(iter.clone()).expect("checked is_some above"); let err = diagnostics::MveExtraTokens { span, ident_span: ident.span, @@ -71,7 +74,7 @@ impl MetaVarExpr { return Err(psess.dcx().create_err(err)); } - let mut iter = args.iter(); + let mut iter = iter.stream().iter_delimited_contents(bounds); let rslt = match ident.name { sym::concat => parse_concat(&mut iter, psess, outer_span, ident.span)?, sym::count => parse_count(&mut iter, psess, ident.span)?, @@ -112,7 +115,7 @@ impl MetaVarExpr { /// Checks if there are any remaining tokens (for example, `${ignore($valid, extra)}`) and create /// a diag with the correct arg count if so. fn check_trailing_tokens<'psess>( - iter: &mut TokenStreamIter<'_>, + iter: &mut ArenaTokenTreeIter<'_>, psess: &'psess ParseSess, ident: Ident, ) -> PResult<'psess, ()> { @@ -133,7 +136,7 @@ fn check_trailing_tokens<'psess>( }; let err = diagnostics::MveExtraTokens { - span: iter_span(iter).expect("checked is_none above"), + span: iter_span(iter.clone()).expect("checked is_none above"), ident_span: ident.span, extra_count: iter.count(), @@ -147,10 +150,9 @@ fn check_trailing_tokens<'psess>( } /// Returns a span encompassing all tokens in the iterator if there is at least one item. -fn iter_span(iter: &TokenStreamIter<'_>) -> Option { - let mut iter = iter.clone(); // cloning is cheap +fn iter_span(mut iter: ArenaTokenTreeIter<'_>) -> Option { let first_sp = iter.next()?.span(); - let last_sp = iter.last().map(TokenTree::span).unwrap_or(first_sp); + let last_sp = iter.last().map(ArenaTokenTree::span).unwrap_or(first_sp); let span = first_sp.with_hi(last_sp.hi()); Some(span) } @@ -171,7 +173,7 @@ pub(crate) enum MetaVarExprConcatElem { /// Parse a meta-variable `concat` expression: `concat($metavar, ident, ...)`. fn parse_concat<'psess>( - iter: &mut TokenStreamIter<'_>, + iter: &mut ArenaTokenTreeIter<'_>, psess: &'psess ParseSess, outer_span: Span, expr_ident_span: Span, @@ -215,7 +217,7 @@ fn parse_concat<'psess>( /// Parse a meta-variable `count` expression: `count(ident[, depth])` fn parse_count<'psess>( - iter: &mut TokenStreamIter<'_>, + iter: &mut ArenaTokenTreeIter<'_>, psess: &'psess ParseSess, span: Span, ) -> PResult<'psess, MetaVarExpr> { @@ -237,12 +239,12 @@ fn parse_count<'psess>( /// Parses the depth used by index(depth) and len(depth). fn parse_depth<'psess>( - iter: &mut TokenStreamIter<'_>, + iter: &mut ArenaTokenTreeIter<'_>, psess: &'psess ParseSess, span: Span, ) -> PResult<'psess, usize> { let Some(tt) = iter.next() else { return Ok(0) }; - let TokenTree::Token(Token { kind: TokenKind::Literal(lit), .. }, _) = tt else { + let ArenaTokenTree::Token(Token { kind: TokenKind::Literal(lit), .. }, _) = tt else { return Err(psess .dcx() .struct_span_err(span, "meta-variable expression depth must be a literal")); @@ -260,7 +262,7 @@ fn parse_depth<'psess>( /// Parses an generic ident fn parse_ident<'psess>( - iter: &mut TokenStreamIter<'_>, + iter: &mut ArenaTokenTreeIter<'_>, psess: &'psess ParseSess, fallback_span: Span, ) -> PResult<'psess, Ident> { @@ -292,14 +294,14 @@ fn parse_ident_from_token<'psess>( } fn parse_token<'psess, 't>( - iter: &mut TokenStreamIter<'t>, + iter: &mut ArenaTokenTreeIter<'t>, psess: &'psess ParseSess, fallback_span: Span, ) -> PResult<'psess, &'t Token> { let Some(tt) = iter.next() else { return Err(psess.dcx().struct_span_err(fallback_span, UNSUPPORTED_CONCAT_ELEM_ERR)); }; - let TokenTree::Token(token, _) = tt else { + let ArenaTokenTree::Token(token, _) = tt else { return Err(psess.dcx().struct_span_err(tt.span(), UNSUPPORTED_CONCAT_ELEM_ERR)); }; Ok(token) @@ -307,8 +309,8 @@ fn parse_token<'psess, 't>( /// Tries to move the iterator forward returning `true` if there is a comma. If not, then the /// iterator is not modified and the result is `false`. -fn try_eat_comma(iter: &mut TokenStreamIter<'_>) -> bool { - if let Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) = iter.peek() { +fn try_eat_comma(iter: &mut ArenaTokenTreeIter<'_>) -> bool { + if let Some(ArenaTokenTree::Token(Token { kind: token::Comma, .. }, _)) = iter.peek() { let _ = iter.next(); return true; } @@ -317,8 +319,8 @@ fn try_eat_comma(iter: &mut TokenStreamIter<'_>) -> bool { /// Tries to move the iterator forward returning `true` if there is a dollar sign. If not, then the /// iterator is not modified and the result is `false`. -fn try_eat_dollar(iter: &mut TokenStreamIter<'_>) -> bool { - if let Some(TokenTree::Token(Token { kind: token::Dollar, .. }, _)) = iter.peek() { +fn try_eat_dollar(iter: &mut ArenaTokenTreeIter<'_>) -> bool { + if let Some(ArenaTokenTree::Token(Token { kind: token::Dollar, .. }, _)) = iter.peek() { let _ = iter.next(); return true; } @@ -327,7 +329,7 @@ fn try_eat_dollar(iter: &mut TokenStreamIter<'_>) -> bool { /// Expects that the next item is a dollar sign. fn eat_dollar<'psess>( - iter: &mut TokenStreamIter<'_>, + iter: &mut ArenaTokenTreeIter<'_>, psess: &'psess ParseSess, span: Span, ) -> PResult<'psess, ()> { diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index 2779291abf361..a1a4662821cd0 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -1,6 +1,8 @@ +use rustc_ast::NodeId; use rustc_ast::token::{self, Delimiter, IdentIsRaw, NonterminalKind, Token}; -use rustc_ast::tokenstream::TokenStreamIter; -use rustc_ast::{NodeId, tokenstream}; +use rustc_ast::tokenarena::{ + ArenaTokenStream, ArenaTokenStreamBuilder, ArenaTokenTree, ArenaTokenTreeIter, +}; use rustc_ast_pretty::pprust; use rustc_errors::Applicability; use rustc_feature::Features; @@ -59,7 +61,7 @@ impl RulePart { /// /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`. fn parse( - input: &tokenstream::TokenStream, + mut iter: ArenaTokenTreeIter<'_>, part: RulePart, sess: &Session, node_id: NodeId, @@ -71,7 +73,6 @@ fn parse( // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming // additional trees if need be. - let mut iter = input.iter(); while let Some(tree) = iter.next() { // Given the parsed tree, if there is a metavar and we are expecting matchers, actually // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`). @@ -104,7 +105,7 @@ fn parse( // Not consuming the next token immediately, as it may not be a colon if let Some(peek) = iter.peek() - && let tokenstream::TokenTree::Token(token, _spacing) = peek + && let ArenaTokenTree::Token(token, _spacing) = peek && let Token { kind: token::Colon, span: colon_span } = token { // Next token is a colon; consume it @@ -112,7 +113,7 @@ fn parse( // It's ok to consume the next tree no matter how, // since if it's not a token then it will be an invalid declaration. - let Some(tokenstream::TokenTree::Token(token, _)) = iter.next() else { + let Some(ArenaTokenTree::Token(token, _)) = iter.next() else { // Invalid, return a nice source location as `var:` result.push(missing_fragment_specifier( colon_span.with_lo(start_sp.lo()), @@ -127,7 +128,7 @@ fn parse( && iter.peek().is_some_and(|next| { matches!( next, - tokenstream::TokenTree::Token(next_token, _) + ArenaTokenTree::Token(next_token, _) if next_token.ident().is_some() ) }) @@ -184,16 +185,28 @@ fn parse( /// single token tree. Emits errors to `sess` if needed. #[inline] pub(super) fn parse_one_tt( - input: tokenstream::TokenTree, + tt: ArenaTokenTree, + stream: &ArenaTokenStream, part: RulePart, sess: &Session, node_id: NodeId, features: &Features, edition: Edition, ) -> TokenTree { - parse(&tokenstream::TokenStream::new(vec![input]), part, sess, node_id, features, edition) - .pop() - .unwrap() + let mut tokens = match tt { + ArenaTokenTree::Token(_, _) => { + let mut builder = ArenaTokenStreamBuilder::with_capacity(1); + builder.push_token_tree(&tt, stream); + let stream = builder.finish(); + let iter = stream.iter_top_level_trees(); + parse(iter, part, sess, node_id, features, edition) + } + ArenaTokenTree::DelimitedStart(bounds, _) => { + let iter = stream.iter_delimited(&bounds); + parse(iter, part, sess, node_id, features, edition) + } + }; + tokens.pop().unwrap() } /// Asks for the `macro_metavar_expr` feature if it is not enabled @@ -226,25 +239,26 @@ fn maybe_emit_macro_metavar_expr_concat_feature(features: &Features, sess: &Sess /// - `sess`: the parsing session. Any errors will be emitted to this session. /// - `features`: language features so we can do feature gating. fn parse_tree<'a>( - tree: &'a tokenstream::TokenTree, - outer_iter: &mut TokenStreamIter<'a>, + tree: &'a ArenaTokenTree, + outer_iter: &mut ArenaTokenTreeIter<'_>, part: RulePart, sess: &Session, node_id: NodeId, features: &Features, edition: Edition, ) -> TokenTree { + let stream = outer_iter.stream().clone(); // Depending on what `tree` is, we could be parsing different parts of a macro match tree { // `tree` is a `$` token. Look at the next token in `trees` - &tokenstream::TokenTree::Token(Token { kind: token::Dollar, span: dollar_span }, _) => { + &ArenaTokenTree::Token(Token { kind: token::Dollar, span: dollar_span }, _) => { // FIXME: Handle `Invisible`-delimited groups in a more systematic way // during parsing. let mut next = outer_iter.next(); let mut iter_storage; - let iter: &mut TokenStreamIter<'_> = match next { - Some(tokenstream::TokenTree::Delimited(.., delim, tts)) if delim.skip() => { - iter_storage = tts.iter(); + let iter: &mut ArenaTokenTreeIter<'_> = match next { + Some(ArenaTokenTree::DelimitedStart(bounds, data)) if data.delimiter.skip() => { + iter_storage = outer_iter.stream().iter_delimited_contents(bounds); next = iter_storage.next(); &mut iter_storage } @@ -253,7 +267,9 @@ fn parse_tree<'a>( match next { // `tree` is followed by a delimited set of token trees. - Some(&tokenstream::TokenTree::Delimited(delim_span, _, delim, ref tts)) => { + Some(&ArenaTokenTree::DelimitedStart(bounds, data)) => { + let delim = data.delimiter; + let delim_span = data.span; if part.is_pattern() { if delim != Delimiter::Parenthesis { span_dollar_dollar_or_metavar_in_the_lhs_err( @@ -270,7 +286,11 @@ fn parse_tree<'a>( // The delimiter is `{`. This indicates the beginning // of a meta-variable expression (e.g. `${count(ident)}`). // Try to parse the meta-variable expression. - match MetaVarExpr::parse(tts, delim_span.entire(), &sess.psess) { + match MetaVarExpr::parse( + outer_iter.stream().iter_delimited_contents(&bounds), + delim_span.entire(), + &sess.psess, + ) { Err(err) => { err.emit(); // Returns early the same read `$` to avoid spanning @@ -309,7 +329,14 @@ fn parse_tree<'a>( // If we didn't find a metavar expression above, then we must have a // repetition sequence in the macro (e.g. `$(pat)*`). Parse the // contents of the sequence itself - let sequence = parse(tts, part, sess, node_id, features, edition); + let sequence = parse( + stream.iter_delimited_contents(&bounds), + part, + sess, + node_id, + features, + edition, + ); // Get the Kleene operator and optional separator let (separator, kleene) = parse_sep_and_kleene_op(iter, delim_span.entire(), sess); @@ -324,7 +351,7 @@ fn parse_tree<'a>( // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` // special metavariable that names the crate of the invocation. - Some(tokenstream::TokenTree::Token(token, _)) if token.is_ident() => { + Some(ArenaTokenTree::Token(token, _)) if token.is_ident() => { let (ident, is_raw) = token.ident().unwrap(); let span = ident.span.with_lo(dollar_span.lo()); if ident.name == kw::Crate && matches!(is_raw, IdentIsRaw::No) { @@ -335,7 +362,7 @@ fn parse_tree<'a>( } // `tree` is followed by another `$`. This is an escaped `$`. - Some(&tokenstream::TokenTree::Token( + Some(&ArenaTokenTree::Token( Token { kind: token::Dollar, span: dollar_span2 }, _, )) => { @@ -351,7 +378,7 @@ fn parse_tree<'a>( } // `tree` is followed by some other token. This is an error. - Some(tokenstream::TokenTree::Token(token, _)) => { + Some(ArenaTokenTree::Token(token, _)) => { let msg = format!("expected identifier, found `{}`", pprust::token_to_string(token),); sess.dcx().span_err(token.span, msg); @@ -364,14 +391,24 @@ fn parse_tree<'a>( } // `tree` is an arbitrary token. Keep it. - tokenstream::TokenTree::Token(token, _) => TokenTree::Token(*token), + ArenaTokenTree::Token(token, _) => TokenTree::Token(*token), // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to // descend into the delimited set and further parse it. - &tokenstream::TokenTree::Delimited(span, spacing, delim, ref tts) => TokenTree::Delimited( - span, - spacing, - Delimited { delim, tts: parse(tts, part, sess, node_id, features, edition) }, + ArenaTokenTree::DelimitedStart(bounds, data) => TokenTree::Delimited( + data.span, + data.spacing, + Delimited { + delim: data.delimiter, + tts: parse( + outer_iter.stream().iter_delimited_contents(bounds), + part, + sess, + node_id, + features, + edition, + ), + }, ), } } @@ -393,15 +430,15 @@ fn kleene_op(token: &Token) -> Option { /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp /// - Err(span) if the next token tree is not a token fn parse_kleene_op( - iter: &mut TokenStreamIter<'_>, + iter: &mut ArenaTokenTreeIter<'_>, span: Span, ) -> Result, Span> { match iter.next() { - Some(tokenstream::TokenTree::Token(token, _)) => match kleene_op(token) { + Some(ArenaTokenTree::Token(token, _)) => match kleene_op(token) { Some(op) => Ok(Ok((op, token.span))), None => Ok(Err(*token)), }, - tree => Err(tree.map_or(span, tokenstream::TokenTree::span)), + tree => Err(tree.map_or(span, ArenaTokenTree::span)), } } @@ -418,7 +455,7 @@ fn parse_kleene_op( /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an /// error with the appropriate span is emitted to `sess` and a dummy value is returned. fn parse_sep_and_kleene_op( - iter: &mut TokenStreamIter<'_>, + iter: &mut ArenaTokenTreeIter<'_>, span: Span, sess: &Session, ) -> (Option, KleeneToken) { diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index eabec05cd66c6..2b8663047dbd1 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -3,7 +3,10 @@ use std::mem; use rustc_ast::token::{ self, Delimiter, IdentIsRaw, InvisibleOrigin, Lit, LitKind, MetaVarKind, Token, TokenKind, }; -use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; +use rustc_ast::tokenarena::{ + ArenaTokenStream, ArenaTokenStreamBuilder, ArenaTokenTree, DelimitedData, +}; +use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing}; use rustc_ast::{ExprKind, StmtKind, TyKind, UnOp}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Diag, DiagCtxtHandle, PResult, listify, pluralize}; @@ -64,11 +67,11 @@ struct TranscrCtx<'psess, 'itp> { /// /// Thus, if we try to pop the `result_stack` and it is empty, we have reached the top-level /// again, and we are done transcribing. - result: Vec, + result: ArenaTokenStreamBuilder, /// The in-progress `result` lives at the top of this stack. Each entered `TokenTree` adds a /// new entry. - result_stack: Vec>, + result_stack: Vec, } impl<'psess> TranscrCtx<'psess, '_> { @@ -170,10 +173,10 @@ pub(super) fn transcribe<'a>( src_span: DelimSpan, transparency: Transparency, expand_id: LocalExpnId, -) -> PResult<'a, TokenStream> { +) -> PResult<'a, ArenaTokenStream> { // Nothing for us to transcribe... if src.tts.is_empty() { - return Ok(TokenStream::default()); + return Ok(ArenaTokenStream::default()); } let mut tscx = TranscrCtx { @@ -186,7 +189,7 @@ pub(super) fn transcribe<'a>( src_span, DelimSpacing::new(Spacing::Alone, Spacing::Alone) )], - result: Vec::new(), + result: ArenaTokenStreamBuilder::default(), result_stack: Vec::new(), }; @@ -205,7 +208,7 @@ pub(super) fn transcribe<'a>( if repeat_idx < repeat_len { frame.idx = 0; if let Some(sep) = sep { - tscx.result.push(TokenTree::Token(*sep, Spacing::Alone)); + tscx.result.push_token_alone(*sep); } continue; } @@ -231,14 +234,20 @@ pub(super) fn transcribe<'a>( } if tscx.result_stack.is_empty() { // No results left to compute! We are back at the top-level. - return Ok(TokenStream::new(tscx.result)); + return Ok(tscx.result.finish()); } // Step back into the parent Delimited. - let tree = - TokenTree::Delimited(span, spacing, delim, TokenStream::new(tscx.result)); + // FIXME: optimize wrap top-level + let mut builder = ArenaTokenStreamBuilder::default(); + builder.push_delimited( + |builder| { + builder.push_stream(tscx.result.finish()); + }, + DelimitedData { span, spacing, delimiter: delim }, + ); tscx.result = tscx.result_stack.pop().unwrap(); - tscx.result.push(tree); + tscx.result.push_stream(builder.finish()); } } continue; @@ -281,8 +290,7 @@ pub(super) fn transcribe<'a>( if let token::NtIdent(ident, _) | token::NtLifetime(ident, _) = &mut token.kind { tscx.marker.mark_span(&mut ident.span); } - let tt = TokenTree::Token(token, Spacing::Alone); - tscx.result.push(tt); + tscx.result.push_token_alone(token); } // There should be no meta-var declarations in the invocation of a macro. @@ -434,90 +442,126 @@ fn transcribe_metavar<'tx>( // with modified syntax context. (I believe this supports nested macros). tscx.marker.mark_span(&mut sp); tscx.marker.mark_span(&mut original_ident.span); - tscx.result.push(TokenTree::token_joint_hidden(token::Dollar, sp)); - tscx.result.push(TokenTree::Token(Token::from_ast_ident(original_ident), Spacing::Alone)); + tscx.result.push_token(Token::new(token::Dollar, sp), Spacing::JointHidden); + tscx.result.push_token_alone(Token::from_ast_ident(original_ident)); return Ok(()); }; - let MatchedSingle(pnr) = cur_matched else { + let MatchedSingle(pnr, stream) = cur_matched else { // We were unable to descend far enough. This is an error. return Err(dcx.create_err(MacroVarStillRepeating { span: sp, ident })); }; - transcribe_pnr(tscx, sp, pnr) + transcribe_pnr(tscx, sp, pnr, stream) } fn transcribe_pnr<'tx>( tscx: &mut TranscrCtx<'tx, '_>, mut sp: Span, pnr: &ParseNtResult, + stream: &ArenaTokenStream, ) -> PResult<'tx, ()> { // We wrap the tokens in invisible delimiters, unless they are already wrapped // in invisible delimiters with the same `MetaVarKind`. Because some proc // macros can't handle multiple layers of invisible delimiters of the same // `MetaVarKind`. This loses some span info, though it hopefully won't matter. - let mut mk_delimited = |mk_span, mv_kind, mut stream: TokenStream| { - if stream.len() == 1 { - let tree = stream.iter().next().unwrap(); - if let TokenTree::Delimited(_, _, delim, inner) = tree - && let Delimiter::Invisible(InvisibleOrigin::MetaVar(mvk)) = delim - && mv_kind == *mvk - { - stream = inner.clone(); + let mut mk_delimited = + |mk_span, mv_kind, stream: ArenaTokenStream, builder: &mut ArenaTokenStreamBuilder| { + let mut iter = stream.iter_top_level_trees(); + + let start = builder.start_delimited(); + + // Emit as a token stream within `Delimiter::Invisible` to maintain + // parsing priorities. + tscx.marker.mark_span(&mut sp); + with_metavar_spans(|mspans| mspans.insert(mk_span, sp)); + // Both the open delim and close delim get the same span, which covers the + // `$foo` in the decl macro RHS. + + if iter.has_single_tree() { + let tree = iter.next().unwrap(); + if let ArenaTokenTree::DelimitedStart(bounds, data) = tree + && let Delimiter::Invisible(InvisibleOrigin::MetaVar(mvk)) = data.delimiter + && mv_kind == mvk + { + builder.push_iter(stream.iter_delimited_contents(bounds)); + } else { + builder.push_stream(stream); + } + } else { + builder.push_stream(stream); } - } - // Emit as a token stream within `Delimiter::Invisible` to maintain - // parsing priorities. - tscx.marker.mark_span(&mut sp); - with_metavar_spans(|mspans| mspans.insert(mk_span, sp)); - // Both the open delim and close delim get the same span, which covers the - // `$foo` in the decl macro RHS. - TokenTree::Delimited( - DelimSpan::from_single(sp), - DelimSpacing::new(Spacing::Alone, Spacing::Alone), - Delimiter::Invisible(InvisibleOrigin::MetaVar(mv_kind)), - stream, - ) - }; + builder.close_delimited( + start, + DelimitedData { + span: DelimSpan::from_single(sp), + spacing: DelimSpacing::new(Spacing::Alone, Spacing::Alone), + delimiter: Delimiter::Invisible(InvisibleOrigin::MetaVar(mv_kind)), + }, + ); + }; - let tt = match pnr { + match pnr { ParseNtResult::Tt(tt) => { // `tt`s are emitted into the output stream directly as "raw tokens", // without wrapping them into groups. Other variables are emitted into // the output stream as groups with `Delimiter::Invisible` to maintain // parsing priorities. - maybe_use_metavar_location(tscx.psess, &tscx.stack, sp, tt, &mut tscx.marker) + maybe_use_metavar_location( + tscx.psess, + &tscx.stack, + sp, + tt, + stream, + &mut tscx.marker, + &mut tscx.result, + ); } ParseNtResult::Ident(ident, is_raw) => { tscx.marker.mark_span(&mut sp); with_metavar_spans(|mspans| mspans.insert(ident.span, sp)); let kind = token::NtIdent(*ident, *is_raw); - TokenTree::token_alone(kind, sp) + tscx.result.push_token_alone(Token::new(kind, sp)); } ParseNtResult::Lifetime(ident, is_raw) => { tscx.marker.mark_span(&mut sp); with_metavar_spans(|mspans| mspans.insert(ident.span, sp)); let kind = token::NtLifetime(*ident, *is_raw); - TokenTree::token_alone(kind, sp) + tscx.result.push_token_alone(Token::new(kind, sp)); } ParseNtResult::Item(item) => { - mk_delimited(item.span, MetaVarKind::Item, TokenStream::from_ast(item)) + mk_delimited( + item.span, + MetaVarKind::Item, + ArenaTokenStream::from_ast(item), + &mut tscx.result, + ); } ParseNtResult::Block(block) => { - mk_delimited(block.node.span, MetaVarKind::Block, TokenStream::from_ast(block)) + mk_delimited( + block.node.span, + MetaVarKind::Block, + ArenaTokenStream::from_ast(block), + &mut tscx.result, + ); } ParseNtResult::Stmt(stmt) => { let stream = if let StmtKind::Empty = stmt.kind { // FIXME: Properly collect tokens for empty statements. - TokenStream::token_alone(token::Semi, stmt.span) + ArenaTokenStream::token_alone(token::Semi, stmt.span) } else { - TokenStream::from_ast(stmt) + ArenaTokenStream::from_ast(stmt) }; - mk_delimited(stmt.span, MetaVarKind::Stmt, stream) + mk_delimited(stmt.span, MetaVarKind::Stmt, stream, &mut tscx.result); } ParseNtResult::Pat(pat, pat_kind) => { - mk_delimited(pat.node.span, MetaVarKind::Pat(*pat_kind), TokenStream::from_ast(pat)) + mk_delimited( + pat.node.span, + MetaVarKind::Pat(*pat_kind), + ArenaTokenStream::from_ast(pat), + &mut tscx.result, + ); } ParseNtResult::Expr(expr, kind) => { let (can_begin_literal_maybe_minus, can_begin_string_literal) = match &expr.kind { @@ -534,29 +578,51 @@ fn transcribe_pnr<'tx>( can_begin_literal_maybe_minus, can_begin_string_literal, }, - TokenStream::from_ast(expr), - ) + ArenaTokenStream::from_ast(expr), + &mut tscx.result, + ); } ParseNtResult::Literal(lit) => { - mk_delimited(lit.span, MetaVarKind::Literal, TokenStream::from_ast(lit)) + mk_delimited( + lit.span, + MetaVarKind::Literal, + ArenaTokenStream::from_ast(lit), + &mut tscx.result, + ); } ParseNtResult::Ty(ty) => { let is_path = matches!(&ty.node.kind, TyKind::Path(None, _path)); - mk_delimited(ty.node.span, MetaVarKind::Ty { is_path }, TokenStream::from_ast(ty)) + mk_delimited( + ty.node.span, + MetaVarKind::Ty { is_path }, + ArenaTokenStream::from_ast(ty), + &mut tscx.result, + ); } ParseNtResult::Meta(attr_item) => { let has_meta_form = attr_item.node.meta_kind().is_some(); mk_delimited( attr_item.node.span, MetaVarKind::Meta { has_meta_form }, - TokenStream::from_ast(attr_item), - ) + ArenaTokenStream::from_ast(attr_item), + &mut tscx.result, + ); } ParseNtResult::Path(path) => { - mk_delimited(path.node.span, MetaVarKind::Path, TokenStream::from_ast(path)) + mk_delimited( + path.node.span, + MetaVarKind::Path, + ArenaTokenStream::from_ast(path), + &mut tscx.result, + ); } ParseNtResult::Vis(vis) => { - mk_delimited(vis.node.span, MetaVarKind::Vis, TokenStream::from_ast(vis)) + mk_delimited( + vis.node.span, + MetaVarKind::Vis, + ArenaTokenStream::from_ast(vis), + &mut tscx.result, + ); } ParseNtResult::Guard(guard) => { // FIXME(macro_guard_matcher): @@ -565,18 +631,22 @@ fn transcribe_pnr<'tx>( let leading_if_span = guard.span_with_leading_if.with_hi(guard.span_with_leading_if.lo() + BytePos(2)); - let ts = std::iter::once(TokenTree::token_alone( + // FIXME: optimize this + let mut builder = ArenaTokenStreamBuilder::default(); + builder.push_token_alone(Token::new( token::Ident(kw::If, IdentIsRaw::No), leading_if_span, - )) - .chain(TokenStream::from_ast(&guard.cond).iter().cloned()) - .collect(); - - mk_delimited(guard.span_with_leading_if, MetaVarKind::Guard, ts) + )); + builder.push_stream(ArenaTokenStream::from_ast(&guard.cond)); + mk_delimited( + guard.span_with_leading_if, + MetaVarKind::Guard, + builder.finish(), + &mut tscx.result, + ); } }; - tscx.result.push(tt); Ok(()) } @@ -587,15 +657,16 @@ fn transcribe_metavar_expr<'tx>( expr: &MetaVarExpr, ) -> PResult<'tx, ()> { let dcx = tscx.psess.dcx(); - let tt = match *expr { + match *expr { MetaVarExpr::Concat(ref elements) => metavar_expr_concat(tscx, dspan, elements)?, MetaVarExpr::Count(original_ident, depth) => { let matched = matched_from_ident(dcx, original_ident, tscx.interp)?; let count = count_repetitions(dcx, depth, matched, &tscx.repeats, &dspan)?; - TokenTree::token_alone( + let token = Token::new( TokenKind::lit(token::Integer, sym::integer(count), None), tscx.visited_dspan(dspan), - ) + ); + tscx.result.push_token_alone(token); } MetaVarExpr::Ignore(original_ident) => { // Used to ensure that `original_ident` is present in the LHS @@ -603,25 +674,30 @@ fn transcribe_metavar_expr<'tx>( return Ok(()); } MetaVarExpr::Index(depth) => match tscx.repeats.iter().nth_back(depth) { - Some((index, _)) => TokenTree::token_alone( - TokenKind::lit(token::Integer, sym::integer(*index), None), - tscx.visited_dspan(dspan), - ), + Some((index, _)) => { + let token = Token::new( + TokenKind::lit(token::Integer, sym::integer(*index), None), + tscx.visited_dspan(dspan), + ); + tscx.result.push_token_alone(token); + } None => { return Err(out_of_bounds_err(dcx, tscx.repeats.len(), dspan.entire(), "index")); } }, MetaVarExpr::Len(depth) => match tscx.repeats.iter().nth_back(depth) { - Some((_, length)) => TokenTree::token_alone( - TokenKind::lit(token::Integer, sym::integer(*length), None), - tscx.visited_dspan(dspan), - ), + Some((_, length)) => { + let token = Token::new( + TokenKind::lit(token::Integer, sym::integer(*length), None), + tscx.visited_dspan(dspan), + ); + tscx.result.push_token_alone(token); + } None => { return Err(out_of_bounds_err(dcx, tscx.repeats.len(), dspan.entire(), "len")); } }, }; - tscx.result.push(tt); Ok(()) } @@ -630,7 +706,7 @@ fn metavar_expr_concat<'tx>( tscx: &mut TranscrCtx<'tx, '_>, dspan: DelimSpan, elements: &[MetaVarExprConcatElem], -) -> PResult<'tx, TokenTree> { +) -> PResult<'tx, ()> { let dcx = tscx.psess.dcx(); let mut concatenated = String::new(); for element in elements { @@ -640,7 +716,7 @@ fn metavar_expr_concat<'tx>( MetaVarExprConcatElem::Var(ident) => { let key = MacroRulesNormalizedIdent::new(*ident); match lookup_cur_matched(key, tscx.interp, &tscx.repeats) { - Some(NamedMatch::MatchedSingle(pnr)) => { + Some(NamedMatch::MatchedSingle(pnr, _)) => { extract_symbol_from_pnr(dcx, pnr, ident.span)? } Some(NamedMatch::MatchedSeq(..)) => { @@ -667,13 +743,11 @@ fn metavar_expr_concat<'tx>( } tscx.psess.symbol_gallery.insert(symbol, concatenated_span); + tscx.result.push_token_alone(Token::from_ast_ident(Ident::new(symbol, concatenated_span))); // The current implementation marks the span as coming from the macro regardless of // contexts of the concatenated identifiers but this behavior may change in the // future. - Ok(TokenTree::Token( - Token::from_ast_ident(Ident::new(symbol, concatenated_span)), - Spacing::Alone, - )) + Ok(()) } /// Store the metavariable span for this original span into a side table. @@ -710,9 +784,11 @@ fn maybe_use_metavar_location( psess: &ParseSess, stack: &[Frame<'_>], mut metavar_span: Span, - orig_tt: &TokenTree, + orig_tt: &ArenaTokenTree, + orig_stream: &ArenaTokenStream, marker: &mut Marker, -) -> TokenTree { + builder: &mut ArenaTokenStreamBuilder, +) { let undelimited_seq = matches!( stack.last(), Some(Frame { @@ -727,40 +803,49 @@ fn maybe_use_metavar_location( ); if undelimited_seq { // Do not record metavar spans for tokens from undelimited sequences, for perf reasons. - return orig_tt.clone(); + builder.push_token_tree(orig_tt, orig_stream); + return; } marker.mark_span(&mut metavar_span); let no_collision = match orig_tt { - TokenTree::Token(token, ..) => { + ArenaTokenTree::Token(token, ..) => { with_metavar_spans(|mspans| mspans.insert(token.span, metavar_span)) } - TokenTree::Delimited(dspan, ..) => with_metavar_spans(|mspans| { + ArenaTokenTree::DelimitedStart(_, data) => with_metavar_spans(|mspans| { + let dspan = data.span; mspans.insert(dspan.open, metavar_span) && mspans.insert(dspan.close, metavar_span) && mspans.insert(dspan.entire(), metavar_span) }), }; if no_collision || psess.source_map().is_imported(metavar_span) { - return orig_tt.clone(); + builder.push_token_tree(orig_tt, orig_stream); + return; } // Setting metavar spans for the heuristic spans gives better opportunities for combining them // with neighboring spans even despite their different syntactic contexts. match orig_tt { - TokenTree::Token(Token { kind, span }, spacing) => { + ArenaTokenTree::Token(Token { kind, span }, spacing) => { let span = metavar_span.with_ctxt(span.ctxt()); with_metavar_spans(|mspans| mspans.insert(span, metavar_span)); - TokenTree::Token(Token { kind: *kind, span }, *spacing) + builder.push_token(Token { kind: *kind, span }, *spacing); } - TokenTree::Delimited(dspan, dspacing, delimiter, tts) => { + ArenaTokenTree::DelimitedStart(bounds, data) => { + let dspan = data.span; let open = metavar_span.with_ctxt(dspan.open.ctxt()); let close = metavar_span.with_ctxt(dspan.close.ctxt()); with_metavar_spans(|mspans| { mspans.insert(open, metavar_span) && mspans.insert(close, metavar_span) }); let dspan = DelimSpan::from_pair(open, close); - TokenTree::Delimited(dspan, *dspacing, *delimiter, tts.clone()) + builder.push_delimited( + |builder| { + builder.push_iter(orig_stream.iter_delimited_contents(bounds)); + }, + DelimitedData { span: dspan, spacing: data.spacing, delimiter: data.delimiter }, + ); } } } @@ -779,7 +864,7 @@ fn lookup_cur_matched<'a>( interpolations.get(&ident).map(|mut matched| { for &(idx, _) in repeats { match matched { - MatchedSingle(_) => break, + MatchedSingle(_, _) => break, MatchedSeq(ads) => matched = ads.get(idx).unwrap(), } } @@ -869,7 +954,7 @@ fn lockstep_iter_size( let name = MacroRulesNormalizedIdent::new(*name); match lookup_cur_matched(name, interpolations, repeats) { Some(matched) => match matched { - MatchedSingle(_) => LockstepIterSize::Unconstrained, + MatchedSingle(_, _) => LockstepIterSize::Unconstrained, MatchedSeq(ads) => LockstepIterSize::Constraint(ads.len(), name), }, _ => LockstepIterSize::Unconstrained, @@ -908,7 +993,7 @@ fn count_repetitions<'dx>( // (or at the top-level of `matched` if no depth is given). fn count<'a>(depth_curr: usize, depth_max: usize, matched: &NamedMatch) -> PResult<'a, usize> { match matched { - MatchedSingle(_) => Ok(1), + MatchedSingle(_, _) => Ok(1), MatchedSeq(named_matches) => { if depth_curr == depth_max { Ok(named_matches.len()) @@ -922,7 +1007,7 @@ fn count_repetitions<'dx>( /// Maximum depth fn depth(counter: usize, matched: &NamedMatch) -> usize { match matched { - MatchedSingle(_) => counter, + MatchedSingle(_, _) => counter, MatchedSeq(named_matches) => { let rslt = counter + 1; if let Some(elem) = named_matches.first() { depth(rslt, elem) } else { rslt } @@ -950,7 +1035,7 @@ fn count_repetitions<'dx>( } } - if let MatchedSingle(_) = matched { + if let MatchedSingle(_, _) = matched { return Err(dcx.create_err(CountRepetitionMisplaced { span: sp.entire() })); } @@ -1002,7 +1087,7 @@ fn extract_symbol_from_pnr<'a>( Ok(nt_ident.name) } } - ParseNtResult::Tt(TokenTree::Token( + ParseNtResult::Tt(ArenaTokenTree::Token( Token { kind: TokenKind::Ident(symbol, is_raw), .. }, _, )) => { @@ -1012,7 +1097,7 @@ fn extract_symbol_from_pnr<'a>( Ok(*symbol) } } - ParseNtResult::Tt(TokenTree::Token( + ParseNtResult::Tt(ArenaTokenTree::Token( Token { kind: TokenKind::Literal(Lit { kind: LitKind::Str, symbol, suffix: None }), .. 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..4bae18b5081f6 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -1,5 +1,5 @@ use rustc_ast as ast; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_data_structures::AtomicRef; use rustc_data_structures::profiling::TimingGuard; use rustc_errors::ErrorGuaranteed; @@ -39,8 +39,8 @@ impl base::BangProcMacro for BangProcMacro { &self, ecx: &mut ExtCtxt<'_>, span: Span, - input: TokenStream, - ) -> Result { + input: ArenaTokenStream, + ) -> Result { let _timer = record_expand_proc_macro(ecx, "expand_proc_macro", span); let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace; @@ -66,9 +66,9 @@ impl base::AttrProcMacro for AttrProcMacro { &self, ecx: &mut ExtCtxt<'_>, span: Span, - annotation: TokenStream, - annotated: TokenStream, - ) -> Result { + annotation: ArenaTokenStream, + annotated: ArenaTokenStream, + ) -> Result { let _timer = record_expand_proc_macro(ecx, "expand_proc_macro", span); let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace; @@ -160,10 +160,10 @@ type DeriveClient = pm::bridge::client::Client; pub fn expand_derive_macro( invoc_id: LocalExpnId, - input: TokenStream, + input: ArenaTokenStream, ecx: &mut ExtCtxt<'_>, client: DeriveClient, -) -> Result { +) -> Result { let _timer = ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| { let invoc_expn_data = invoc_id.expn_data(); @@ -195,7 +195,12 @@ pub fn expand_derive_macro( } pub static EXPAND_DERIVE_MACRO_CACHED: AtomicRef< - fn(LocalExpnId, TokenStream, &mut ExtCtxt<'_>, DeriveClient) -> Result, + fn( + LocalExpnId, + ArenaTokenStream, + &mut ExtCtxt<'_>, + DeriveClient, + ) -> Result, > = AtomicRef::new( &(|_, _, _: &mut ExtCtxt<'_>, _| -> Result<_, _> { panic!( diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index c0a9a43c64cdf..3ae52a176702d 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -2,7 +2,11 @@ use std::ops::{Bound, Range}; use rustc_ast as ast; use rustc_ast::token as tk; -use rustc_ast::tokenstream::{self, DelimSpacing, Spacing, TokenStream}; +use rustc_ast::token::Token; +use rustc_ast::tokenarena::{ + ArenaTokenStream, ArenaTokenStreamBuilder, ArenaTokenTree, DelimitedData, +}; +use rustc_ast::tokenstream::{self, DelimSpacing, Spacing}; use rustc_ast::util::literal::escape_byte_str_symbol; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashMap; @@ -18,7 +22,6 @@ use rustc_session::Session; use rustc_session::parse::ParseSess; use rustc_span::def_id::CrateNum; use rustc_span::{BytePos, FileName, Pos, Span, Symbol, sym}; -use smallvec::{SmallVec, smallvec}; use crate::base::ExtCtxt; @@ -103,32 +106,46 @@ impl ToInternal for LitKind { } } -impl FromInternal for Vec> { - fn from_internal(stream: TokenStream) -> Self { +impl FromInternal for Vec> { + fn from_internal(stream: ArenaTokenStream) -> Self { // Estimate the capacity as `stream.len()` rounded up to the next power // of two to limit the number of required reallocations. - let mut trees = Vec::with_capacity(stream.len().next_power_of_two()); + // FIXME: try to estimate the allocation size without iterating through the whole thing + let mut trees = + Vec::with_capacity(stream.iter_top_level_trees().count().next_power_of_two()); + + for tree in stream.iter_top_level_trees() { + let (tk::Token { kind, span }, joint) = match *tree { + ArenaTokenTree::DelimitedStart(mut bounds, data) => { + let span = data.span; + let mut delim = data.delimiter; - for tree in stream.iter() { - let (tk::Token { kind, span }, joint) = match tree.clone() { - tokenstream::TokenTree::Delimited(span, _, mut delim, mut stream) => { // In `mk_delimited` we avoid nesting invisible delimited // of the same `MetaVarKind`. Here we do the same but // ignore the `MetaVarKind` because it is discarded when we // convert it to a `Group`. - while let tk::Delimiter::Invisible(tk::InvisibleOrigin::MetaVar(_)) = delim - && stream.len() == 1 - && let tree = stream.get(0).unwrap() - && let tokenstream::TokenTree::Delimited(_, _, delim2, stream2) = tree - && let tk::Delimiter::Invisible(tk::InvisibleOrigin::MetaVar(_)) = delim2 - { - delim = *delim2; - stream = stream2.clone(); + while let tk::Delimiter::Invisible(tk::InvisibleOrigin::MetaVar(_)) = delim { + let mut iter = stream.iter_delimited_contents(&bounds); + let tree = iter.next(); + let Some(ArenaTokenTree::DelimitedStart(bounds2, data2)) = tree else { + break; + }; + if iter.next().is_some() { + break; + } + let tk::Delimiter::Invisible(tk::InvisibleOrigin::MetaVar(_)) = + data2.delimiter + else { + break; + }; + + delim = data2.delimiter; + bounds = *bounds2; } trees.push(TokenTree::Group(Group { delimiter: rustc_proc_macro::Delimiter::from_internal(delim), - stream: Some(stream), + stream: Some(ArenaTokenStream::separate_delimited_inner(bounds, &stream)), span: DelimSpan { open: span.open, close: span.close, @@ -137,7 +154,7 @@ impl FromInternal for Vec> { })); continue; } - tokenstream::TokenTree::Token(token, spacing) => { + ArenaTokenTree::Token(token, spacing) => { // Do not be tempted to check here that the `spacing` // values are "correct" w.r.t. the token stream (e.g. that // `Spacing::Joint` is actually followed by a `Punct` token @@ -252,7 +269,7 @@ impl FromInternal for Vec> { } tk::NtLifetime(ident, is_raw) => { let stream = - TokenStream::token_alone(tk::Lifetime(ident.name, is_raw), ident.span); + ArenaTokenStream::token_alone(tk::Lifetime(ident.name, is_raw), ident.span); trees.push(TokenTree::Group(Group { delimiter: rustc_proc_macro::Delimiter::None, stream: Some(stream), @@ -273,21 +290,20 @@ impl FromInternal for Vec> { for ch in data.as_str().chars() { escaped.extend(ch.escape_debug()); } - let stream = [ + let tokens = [ tk::Ident(sym::doc, tk::IdentIsRaw::No), tk::Eq, tk::TokenKind::lit(tk::Str, Symbol::intern(&escaped), None), ] .into_iter() - .map(|kind| tokenstream::TokenTree::token_alone(kind, span)) - .collect(); + .map(|kind| (Token::new(kind, span), Spacing::Alone)); trees.push(TokenTree::Punct(Punct { ch: b'#', joint: false, span })); if attr_style == ast::AttrStyle::Inner { trees.push(TokenTree::Punct(Punct { ch: b'!', joint: false, span })); } trees.push(TokenTree::Group(Group { delimiter: rustc_proc_macro::Delimiter::Bracket, - stream: Some(stream), + stream: Some(ArenaTokenStream::from_token_iter(tokens)), span: DelimSpan::from_single(span), })); } @@ -307,97 +323,100 @@ impl FromInternal for Vec> { } } -// We use a `SmallVec` because the output size is always one or two `TokenTree`s. -impl ToInternal> - for (TokenTree, &mut Rustc<'_, '_>) +fn push_tree_to_internal( + tree: TokenTree, + rustc: &mut Rustc<'_, '_>, + builder: &mut ArenaTokenStreamBuilder, + push_token: F, +) where + F: Fn(&mut ArenaTokenStreamBuilder, Token, Spacing), { - fn to_internal(self) -> SmallVec<[tokenstream::TokenTree; 2]> { - // The code below is conservative, using `token_alone`/`Spacing::Alone` - // in most places. It's hard in general to do better when working at - // the token level. When the resulting code is pretty-printed by - // `print_tts` the `space_between` function helps avoid a lot of - // unnecessary whitespace, so the results aren't too bad. - let (tree, rustc) = self; - match tree { - TokenTree::Punct(Punct { ch, joint, span }) => { - let kind = match ch { - b'=' => tk::Eq, - b'<' => tk::Lt, - b'>' => tk::Gt, - b'!' => tk::Bang, - b'~' => tk::Tilde, - b'+' => tk::Plus, - b'-' => tk::Minus, - b'*' => tk::Star, - b'/' => tk::Slash, - b'%' => tk::Percent, - b'^' => tk::Caret, - b'&' => tk::And, - b'|' => tk::Or, - b'@' => tk::At, - b'.' => tk::Dot, - b',' => tk::Comma, - b';' => tk::Semi, - b':' => tk::Colon, - b'#' => tk::Pound, - b'$' => tk::Dollar, - b'?' => tk::Question, - b'\'' => tk::SingleQuote, - _ => unreachable!(), - }; - // We never produce `tk::Spacing::JointHidden` here, which - // means the pretty-printing of code produced by proc macros is - // ugly, with lots of whitespace between tokens. This is - // unavoidable because `proc_macro::Spacing` only applies to - // `Punct` token trees. - smallvec![if joint { - tokenstream::TokenTree::token_joint(kind, span) - } else { - tokenstream::TokenTree::token_alone(kind, span) - }] - } - TokenTree::Group(Group { delimiter, stream, span: DelimSpan { open, close, .. } }) => { - smallvec![tokenstream::TokenTree::Delimited( - tokenstream::DelimSpan { open, close }, - DelimSpacing::new(Spacing::Alone, Spacing::Alone), - delimiter.to_internal(), - stream.unwrap_or_default(), - )] - } - TokenTree::Ident(self::Ident { sym, is_raw, span }) => { - rustc.psess().symbol_gallery.insert(sym, span); - smallvec![tokenstream::TokenTree::token_alone(tk::Ident(sym, is_raw.into()), span)] - } - TokenTree::Literal(self::Literal { - kind: self::LitKind::Integer, - symbol, - suffix, - span, - }) if let Some(symbol) = symbol.as_str().strip_prefix('-') => { - let symbol = Symbol::intern(symbol); - let integer = tk::TokenKind::lit(tk::Integer, symbol, suffix); - let a = tokenstream::TokenTree::token_joint_hidden(tk::Minus, span); - let b = tokenstream::TokenTree::token_alone(integer, span); - smallvec![a, b] - } - TokenTree::Literal(self::Literal { - kind: self::LitKind::Float, - symbol, - suffix, - span, - }) if let Some(symbol) = symbol.as_str().strip_prefix('-') => { - let symbol = Symbol::intern(symbol); - let float = tk::TokenKind::lit(tk::Float, symbol, suffix); - let a = tokenstream::TokenTree::token_joint_hidden(tk::Minus, span); - let b = tokenstream::TokenTree::token_alone(float, span); - smallvec![a, b] - } - TokenTree::Literal(self::Literal { kind, symbol, suffix, span }) => { - smallvec![tokenstream::TokenTree::token_alone( - tk::TokenKind::lit(kind.to_internal(), symbol, suffix), - span, - )] - } + // The code below is conservative, using `token_alone`/`Spacing::Alone` + // in most places. It's hard in general to do better when working at + // the token level. When the resulting code is pretty-printed by + // `print_tts` the `space_between` function helps avoid a lot of + // unnecessary whitespace, so the results aren't too bad. + match tree { + TokenTree::Punct(Punct { ch, joint, span }) => { + let kind = match ch { + b'=' => tk::Eq, + b'<' => tk::Lt, + b'>' => tk::Gt, + b'!' => tk::Bang, + b'~' => tk::Tilde, + b'+' => tk::Plus, + b'-' => tk::Minus, + b'*' => tk::Star, + b'/' => tk::Slash, + b'%' => tk::Percent, + b'^' => tk::Caret, + b'&' => tk::And, + b'|' => tk::Or, + b'@' => tk::At, + b'.' => tk::Dot, + b',' => tk::Comma, + b';' => tk::Semi, + b':' => tk::Colon, + b'#' => tk::Pound, + b'$' => tk::Dollar, + b'?' => tk::Question, + b'\'' => tk::SingleQuote, + _ => unreachable!(), + }; + // We never produce `tk::Spacing::JointHidden` here, which + // means the pretty-printing of code produced by proc macros is + // ugly, with lots of whitespace between tokens. This is + // unavoidable because `proc_macro::Spacing` only applies to + // `Punct` token trees. + let spacing = if joint { Spacing::Joint } else { Spacing::Alone }; + push_token(builder, Token::new(kind, span), spacing); + } + TokenTree::Group(Group { delimiter, stream, span: DelimSpan { open, close, .. } }) => { + builder.push_delimited( + |builder| { + if let Some(stream) = stream { + // Note that we don't call push_token here for the tokens created inside + // `push_stream`. Glueing only happens if the top-level tree is a token, but here + // all tokens will be nested. + builder.push_stream(stream); + } + }, + DelimitedData { + span: tokenstream::DelimSpan { open, close }, + spacing: DelimSpacing::new(Spacing::Alone, Spacing::Alone), + delimiter: delimiter.to_internal(), + }, + ); + } + TokenTree::Ident(self::Ident { sym, is_raw, span }) => { + rustc.psess().symbol_gallery.insert(sym, span); + push_token(builder, Token::new(tk::Ident(sym, is_raw.into()), span), Spacing::Alone); + } + TokenTree::Literal(self::Literal { + kind: self::LitKind::Integer, + symbol, + suffix, + span, + }) if let Some(symbol) = symbol.as_str().strip_prefix('-') => { + let symbol = Symbol::intern(symbol); + let integer = tk::TokenKind::lit(tk::Integer, symbol, suffix); + push_token(builder, Token::new(tk::Minus, span), Spacing::JointHidden); + push_token(builder, Token::new(integer, span), Spacing::Alone); + } + TokenTree::Literal(self::Literal { kind: self::LitKind::Float, symbol, suffix, span }) + if let Some(symbol) = symbol.as_str().strip_prefix('-') => + { + let symbol = Symbol::intern(symbol); + let float = tk::TokenKind::lit(tk::Float, symbol, suffix); + push_token(builder, Token::new(tk::Minus, span), Spacing::JointHidden); + push_token(builder, Token::new(float, span), Spacing::Alone); + } + TokenTree::Literal(self::Literal { kind, symbol, suffix, span }) => { + push_token( + builder, + Token::new(tk::TokenKind::lit(kind.to_internal(), symbol, suffix), span), + Spacing::Alone, + ); } } } @@ -465,7 +484,7 @@ impl<'a, 'b> Rustc<'a, 'b> { } impl server::Server for Rustc<'_, '_> { - type TokenStream = TokenStream; + type TokenStream = ArenaTokenStream; type Span = Span; type Symbol = Symbol; @@ -624,27 +643,27 @@ impl server::Server for Rustc<'_, '_> { // be recovered in the general case. match &expr.kind { ast::ExprKind::Lit(token_lit) if token_lit.kind == tk::Bool => { - Ok(tokenstream::TokenStream::token_alone( + Ok(ArenaTokenStream::token_alone( tk::Ident(token_lit.symbol, tk::IdentIsRaw::No), expr.span, )) } ast::ExprKind::Lit(token_lit) => { - Ok(tokenstream::TokenStream::token_alone(tk::Literal(*token_lit), expr.span)) + Ok(ArenaTokenStream::token_alone(tk::Literal(*token_lit), expr.span)) } ast::ExprKind::IncludedBytes(byte_sym) => { let lit = tk::Lit::new(tk::ByteStr, escape_byte_str_symbol(byte_sym.as_byte_str()), None); - Ok(tokenstream::TokenStream::token_alone(tk::TokenKind::Literal(lit), expr.span)) + Ok(ArenaTokenStream::token_alone(tk::TokenKind::Literal(lit), expr.span)) } ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind { ast::ExprKind::Lit(token_lit) => match token_lit { tk::Lit { kind: tk::Integer | tk::Float, .. } => { - Ok(Self::TokenStream::from_iter([ + Ok(Self::TokenStream::from_token_iter([ // FIXME: The span of the `-` token is lost when // parsing, so we cannot faithfully recover it here. - tokenstream::TokenTree::token_joint_hidden(tk::Minus, e.span), - tokenstream::TokenTree::token_alone(tk::Literal(*token_lit), e.span), + (Token::new(tk::Minus, e.span), Spacing::JointHidden), + (Token::new(tk::Literal(*token_lit), e.span), Spacing::Alone), ])) } _ => Err(()), @@ -659,7 +678,11 @@ impl server::Server for Rustc<'_, '_> { &mut self, tree: TokenTree, ) -> Self::TokenStream { - Self::TokenStream::new((tree, &mut *self).to_internal().into_iter().collect::>()) + let mut builder = ArenaTokenStreamBuilder::default(); + push_tree_to_internal(tree, self, &mut builder, |builder, token, spacing| { + builder.push_token(token, spacing); + }); + builder.finish() } fn ts_concat_trees( @@ -667,13 +690,19 @@ impl server::Server for Rustc<'_, '_> { base: Option, trees: Vec>, ) -> Self::TokenStream { - let mut stream = base.unwrap_or_default(); + let mut builder = if let Some(base) = base { + base.into_builder() + } else { + ArenaTokenStreamBuilder::default() + }; for tree in trees { - for tt in (tree, &mut *self).to_internal() { - stream.push_tree_with_gluing(tt); - } + push_tree_to_internal(tree, self, &mut builder, |builder, token, spacing| { + if !builder.try_glue_to_last_top_level_token(&token, spacing) { + builder.push_token(token, spacing); + } + }); } - stream + builder.finish() } fn ts_concat_streams( @@ -681,11 +710,22 @@ impl server::Server for Rustc<'_, '_> { base: Option, streams: Vec, ) -> Self::TokenStream { - let mut stream = base.unwrap_or_default(); + let mut builder = if let Some(base) = base { + base.into_builder() + } else { + ArenaTokenStreamBuilder::default() + }; for s in streams { - stream.push_stream_with_gluing(s); + let mut iter = s.iter_top_level_trees(); + if let Some(ArenaTokenTree::Token(token, spacing)) = iter.peek() + && builder.try_glue_to_last_top_level_token(&token, *spacing) + { + // Skip the first token, as it was glued + iter.next(); + } + builder.push_iter(iter); } - stream + builder.finish() } fn ts_into_trees( diff --git a/compiler/rustc_expand_queries/src/derive.rs b/compiler/rustc_expand_queries/src/derive.rs index 1254013ad89bb..921ae7265853c 100644 --- a/compiler/rustc_expand_queries/src/derive.rs +++ b/compiler/rustc_expand_queries/src/derive.rs @@ -1,4 +1,4 @@ -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_expand::base::ExtCtxt; use rustc_middle::ty::{TyCtxt, tls}; use rustc_proc_macro as pm; @@ -53,13 +53,13 @@ scoped_tls::scoped_thread_local!(static DERIVE_EXPAND_CTX: QueryDeriveExpandCtx) pub(crate) fn expand_derive_macro_cached( invoc_id: LocalExpnId, - input: TokenStream, + input: ArenaTokenStream, ecx: &mut ExtCtxt<'_>, client: DeriveClient, -) -> Result { +) -> Result { tls::with(|tcx| { let input = &*tcx.arena.alloc(input); - let key: (LocalExpnId, &TokenStream) = (invoc_id, input); + let key: (LocalExpnId, &ArenaTokenStream) = (invoc_id, input); QueryDeriveExpandCtx::enter(ecx, client, move || tcx.derive_macro_expansion(key).cloned()) }) @@ -68,8 +68,8 @@ pub(crate) fn expand_derive_macro_cached( /// Provide a query for computing the output of a derive macro. pub(crate) fn derive_macro_expansion<'tcx>( tcx: TyCtxt<'tcx>, - key: (LocalExpnId, &'tcx TokenStream), -) -> Result<&'tcx TokenStream, ()> { + key: (LocalExpnId, &'tcx ArenaTokenStream), +) -> Result<&'tcx ArenaTokenStream, ()> { let (invoc_id, input) = key; // Make sure that we invalidate the query when the crate defining the proc macro changes diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 6d1ae563a9fa2..5fb14c3a77c37 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, true, span, ), diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index f85a14852d6cd..c37a399c21d43 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -17,7 +17,7 @@ use std::fmt::Write; use ast::token::TokenKind; use rustc_abi::BackendRepr; -use rustc_ast::tokenstream::{TokenStream, TokenTree}; +use rustc_ast::tokenarena::{ArenaTokenTree, ArenaTokenTreeIter}; use rustc_ast::visit::{FnCtxt, FnKind}; use rustc_ast::{self as ast, *}; use rustc_ast_pretty::pprust::expr_to_string; @@ -1751,13 +1751,14 @@ declare_lint_pass!( struct UnderMacro(bool); impl KeywordIdents { - fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: &TokenStream) { + fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: ArenaTokenTreeIter<'_>) { // Check if the preceding token is `$`, because we want to allow `$async`, etc. let mut prev_dollar = false; - for tt in tokens.iter() { + let stream = tokens.stream().clone(); + for tt in tokens { match tt { // Only report non-raw idents. - TokenTree::Token(token, _) => { + ArenaTokenTree::Token(token, _) => { if let Some((ident, token::IdentIsRaw::No)) = token.ident() { if !prev_dollar { self.check_ident_token(cx, UnderMacro(true), ident, ""); @@ -1774,7 +1775,9 @@ impl KeywordIdents { continue; } } - TokenTree::Delimited(.., tts) => self.check_tokens(cx, tts), + ArenaTokenTree::DelimitedStart(bounds, ..) => { + self.check_tokens(cx, stream.iter_delimited_contents(bounds)) + } } prev_dollar = false; } @@ -1826,10 +1829,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.iter_top_level_trees()); } fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) { - self.check_tokens(cx, &mac.args.tokens); + self.check_tokens(cx, mac.args.tokens.iter_top_level_trees()); } 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..d55d07d9159ee 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 @@ -1,7 +1,7 @@ //! Migration code for the `expr_fragment_specifier_2024` rule. use rustc_ast::token::{Token, TokenKind}; -use rustc_ast::tokenstream::{TokenStream, TokenTree}; +use rustc_ast::tokenarena::{ArenaTokenTree, ArenaTokenTreeIter}; use rustc_lint_defs::{declare_lint, declare_lint_pass, fcw}; use rustc_span::edition::Edition; use rustc_span::sym; @@ -78,17 +78,18 @@ declare_lint! { declare_lint_pass!(Expr2024 => [EDITION_2024_EXPR_FRAGMENT_SPECIFIER,]); impl Expr2024 { - fn check_tokens(&mut self, cx: &crate::EarlyContext<'_>, tokens: &TokenStream) { + fn check_tokens(&mut self, cx: &crate::EarlyContext<'_>, tokens: ArenaTokenTreeIter<'_>) { let mut prev_colon = false; let mut prev_identifier = false; let mut prev_dollar = false; - for tt in tokens.iter() { + let stream = tokens.stream().clone(); + for tt in tokens { debug!( "check_tokens: {:?} - colon {prev_dollar} - ident {prev_identifier} - colon {prev_colon}", tt ); match tt { - TokenTree::Token(token, _) => match token.kind { + ArenaTokenTree::Token(token, _) => match token.kind { TokenKind::Dollar => { prev_dollar = true; continue; @@ -109,7 +110,9 @@ impl Expr2024 { } _ => {} }, - TokenTree::Delimited(.., tts) => self.check_tokens(cx, tts), + ArenaTokenTree::DelimitedStart(bounds, _) => { + self.check_tokens(cx, stream.iter_delimited_contents(bounds)) + } } prev_colon = false; prev_identifier = false; @@ -142,6 +145,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.iter_top_level_trees()); } } diff --git a/compiler/rustc_middle/src/arena.rs b/compiler/rustc_middle/src/arena.rs index bfaef6157d02c..b62a85d02ba83 100644 --- a/compiler/rustc_middle/src/arena.rs +++ b/compiler/rustc_middle/src/arena.rs @@ -136,6 +136,7 @@ rustc_arena::declare_arena! { crate_inherent_impls: rustc_middle::ty::CrateInherentImpls, hir_owner_nodes: rustc_hir::OwnerNodes<'tcx>, token_stream: rustc_ast::tokenstream::TokenStream, + arena_token_stream: rustc_ast::tokenarena::ArenaTokenStream, parenting: rustc_hir::def_id::LocalDefIdMap, trait_candidates: rustc_hir::ItemLocalMap<&'tcx [rustc_hir::TraitCandidate<'tcx>]>, delayed_lints: rustc_data_structures::steal::Steal, @@ -195,6 +196,7 @@ impl_ref_decodable_into_arena! { (rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>, rustc_middle::middle::exported_symbols::SymbolExportInfo), rustc_ast::InlineAsmTemplatePiece, rustc_ast::tokenstream::TokenStream, + rustc_ast::tokenarena::ArenaTokenStream, rustc_data_structures::unord::UnordMap>>, rustc_data_structures::unord::UnordSet, rustc_hir::Attribute, diff --git a/compiler/rustc_middle/src/queries.rs b/compiler/rustc_middle/src/queries.rs index c01ffb6a9caac..8094e8aae18f5 100644 --- a/compiler/rustc_middle/src/queries.rs +++ b/compiler/rustc_middle/src/queries.rs @@ -52,7 +52,7 @@ use rustc_abi::Align; use rustc_arena::TypedArena; use rustc_ast as ast; use rustc_ast::expand::allocator::AllocatorKind; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_attr_ir::lang_items::{LangItem, LanguageItems}; use rustc_attr_ir::{CanonicalSymbols, EiiDecl, EiiImpl, StrippedCfgItem}; use rustc_crate_store::{ @@ -148,7 +148,7 @@ rustc_queries! { /// - Token stream which serves as an input to the macro. /// /// The output is the token stream generated by the proc macro. - query derive_macro_expansion(key: (LocalExpnId, &'tcx TokenStream)) -> Result<&'tcx TokenStream, ()> { + query derive_macro_expansion(key: (LocalExpnId, &'tcx ArenaTokenStream)) -> Result<&'tcx ArenaTokenStream, ()> { desc { "expanding a derive (proc) macro" } cache_on_disk } diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index 15a684491dcab..cf20fc3ef8b4c 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -10,7 +10,7 @@ use std::intrinsics::transmute_unchecked; use std::marker::PhantomData; use std::mem::MaybeUninit; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_data_structures::steal::Steal; use rustc_data_structures::sync::{DynSend, DynSync}; use rustc_index::{Idx, IndexSlice}; @@ -204,7 +204,7 @@ impl_erasable_for_types_with_no_type_params! { Option>>, Option>, Option, - Result<&'_ TokenStream, ()>, + Result<&'_ ArenaTokenStream, ()>, Result<&'_ rustc_target::callconv::FnAbi<'_, Ty<'_>>, &'_ ty::layout::FnAbiError<'_>>, Result<&'_ traits::ImplSource<'_, ()>, traits::CodegenObligationError>, Result<&'_ ty::List>, ty::util::AlwaysRequiresDrop>, diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index eae4148a30ed4..cec91b09b2007 100644 --- a/compiler/rustc_middle/src/query/keys.rs +++ b/compiler/rustc_middle/src/query/keys.rs @@ -4,7 +4,7 @@ use std::ffi::OsStr; use std::fmt::Debug; use std::hash::Hash; -use rustc_ast::tokenstream::TokenStream; +use rustc_ast::tokenarena::ArenaTokenStream; use rustc_data_structures::sso::SsoHashSet; use rustc_data_structures::stable_hash::StableHash; use rustc_hir::OwnerId; @@ -394,7 +394,7 @@ impl<'tcx> QueryKey for ty::Value<'tcx> { } } -impl<'tcx> QueryKey for (LocalExpnId, &'tcx TokenStream) { +impl<'tcx> QueryKey for (LocalExpnId, &'tcx ArenaTokenStream) { fn default_span(&self, _tcx: TyCtxt<'_>) -> Span { self.0.expn_data().call_site } diff --git a/compiler/rustc_middle/src/query/on_disk_cache.rs b/compiler/rustc_middle/src/query/on_disk_cache.rs index 1fa0aa421d584..5c8db0f67d36c 100644 --- a/compiler/rustc_middle/src/query/on_disk_cache.rs +++ b/compiler/rustc_middle/src/query/on_disk_cache.rs @@ -744,7 +744,7 @@ impl<'a, 'tcx> Decodable> } } -impl<'a, 'tcx> Decodable> for &'tcx rustc_ast::tokenstream::TokenStream { +impl<'a, 'tcx> Decodable> for &'tcx rustc_ast::tokenarena::ArenaTokenStream { #[inline] fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self { RefDecodable::decode(d) diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index 2afb55b02e2e6..f31c166260b2b 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..ac65e1194f78d 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.current_index(); + let open_spacing = self.lex_token_trees(token_builder, /* is_delimited */ true)?; + let lexed_trees = token_builder.tree_count_since(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 16a438b5387ee..ce5f7fec3bcb4 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, 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,64 @@ 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 builder = 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 builder); } - 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 builder)?; + let Some(ArenaTokenTree::Token(semi, _)) = builder.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)) + + builder.push_delimited( + |builder| { + lex_token_trees_for_span(psess, spans.inner_span.until(attr.span), builder)?; + lex_token_trees_for_span( + psess, + attr.span.between(spans.inner_span.shrink_to_hi()), + builder, + )?; + Some(()) + }, + DelimitedData { + span: DelimSpan::from_single(semi.span), + spacing: DelimSpacing::new(Spacing::Alone, Spacing::Alone), + delimiter: token::Delimiter::Brace, + }, + )?; + + Some(builder.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..2a05f5adb5297 100644 --- a/compiler/rustc_parse/src/parser/cfg_select.rs +++ b/compiler/rustc_parse/src/parser/cfg_select.rs @@ -1,5 +1,5 @@ use rustc_ast::token; -use rustc_ast::tokenstream::{TokenStream, TokenTree}; +use rustc_ast::tokenarena::{ArenaTokenStream, ArenaTokenTree}; use rustc_ast::util::classify; use rustc_errors::PResult; use rustc_span::Span; @@ -16,15 +16,18 @@ pub struct CfgSelectBranchAttrSpans { impl<'a> Parser<'a> { /// Parses the right-hand side of a `cfg_select!` branch, /// which can be either a braced block or an expression. - pub fn parse_cfg_select_branch_rhs(&mut self) -> PResult<'a, TokenStream> { + pub fn parse_cfg_select_branch_rhs(&mut self) -> PResult<'a, ArenaTokenStream> { 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 '{{'"), + ArenaTokenTree::DelimitedStart(bounds, _) => { // Optionally end with a comma. let _ = self.eat(exp!(Comma)); - return Ok(tts); + return Ok(ArenaTokenStream::separate_delimited_inner( + bounds, + &self.token_cursor.stream, + )); } } } @@ -46,6 +49,6 @@ impl<'a> Parser<'a> { } else { let _ = self.eat(exp!(Comma)); } - Ok(TokenStream::from_ast(&expr)) + Ok(ArenaTokenStream::from_ast(&expr)) } } diff --git a/compiler/rustc_parse/src/parser/function.rs b/compiler/rustc_parse/src/parser/function.rs index 220cc5a3bc069..87535e80336da 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}; @@ -358,8 +358,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 @@ -367,17 +367,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 d4717b88bbb14..0a4c11d9b5e22 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::*; @@ -1096,7 +1097,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 @@ -1640,7 +1641,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) } @@ -2580,8 +2581,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..ed56e0eed6609 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -29,9 +29,8 @@ pub use path::PathStyle; use rustc_ast::token::{ self, IdentIsRaw, InvisibleOrigin, MetaVarKind, NtExprKind, NtPatKind, Token, TokenKind, }; -use rustc_ast::tokenstream::{ - ParserRange, ParserReplacement, Spacing, TokenCursor, TokenStream, TokenTree, WithTokens, -}; +use rustc_ast::tokenarena::{ArenaTokenStream, ArenaTokenStreamBuilder, ArenaTokenTree}; +use rustc_ast::tokenstream::{ParserRange, ParserReplacement, Spacing, TokenCursor, WithTokens}; use rustc_ast::util::case::Case; use rustc_ast::util::classify; use rustc_ast::{ @@ -243,11 +242,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 +347,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 +508,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 ) } @@ -1156,10 +1161,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 +1208,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) } @@ -1376,20 +1384,27 @@ 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,20 +1440,20 @@ 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) } } - pub fn parse_tokens(&mut self) -> TokenStream { - let mut result = Vec::new(); + pub fn parse_tokens(&mut self) -> ArenaTokenStream { + let mut builder = ArenaTokenStreamBuilder::default(); loop { if self.token.kind.is_close_delim_or_eof() { break; } else { - result.push(self.parse_token_tree()); + builder.push_token_tree(&self.parse_token_tree(), &self.token_cursor.stream); } } - TokenStream::new(result) + builder.finish() } /// Evaluates the closure with restrictions in place. @@ -1806,7 +1821,7 @@ impl<'a> Parser<'a> { // smaller. #[derive(Clone, Debug)] pub enum ParseNtResult { - Tt(TokenTree), + Tt(ArenaTokenTree), Ident(Ident, IdentIsRaw), Lifetime(Ident, IdentIsRaw), Item(Box), 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