3 //! `TokenStream`s represent syntactic objects before they are converted into ASTs.
4 //! A `TokenStream` is, roughly speaking, a sequence of [`TokenTree`]s,
5 //! which are themselves a single [`Token`] or a `Delimited` subsequence of tokens.
9 //! `TokenStream`s are persistent data structures constructed as ropes with reference
10 //! counted-children. In general, this means that calling an operation on a `TokenStream`
11 //! (such as `slice`) produces an entirely new `TokenStream` from the borrowed reference to
12 //! the original. This essentially coerces `TokenStream`s into "views" of their subparts,
13 //! and a borrowed `TokenStream` is sufficient to build an owned `TokenStream` without taking
14 //! ownership of the original.
16 use crate::ast::StmtKind;
17 use crate::ast_traits::{HasAttrs, HasSpan, HasTokens};
18 use crate::token::{self, Delimiter, Nonterminal, Token, TokenKind};
21 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
22 use rustc_data_structures::sync::{self, Lrc};
23 use rustc_macros::HashStable_Generic;
24 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
25 use rustc_span::{Span, DUMMY_SP};
26 use smallvec::{smallvec, SmallVec};
30 /// When the main Rust parser encounters a syntax-extension invocation, it
31 /// parses the arguments to the invocation as a token tree. This is a very
32 /// loose structure, such that all sorts of different AST fragments can
33 /// be passed to syntax extensions using a uniform type.
35 /// If the syntax extension is an MBE macro, it will attempt to match its
36 /// LHS token tree against the provided token tree, and if it finds a
37 /// match, will transcribe the RHS token tree, splicing in any captured
38 /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
40 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
41 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
42 #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
45 Token(Token, Spacing),
46 /// A delimited sequence of token trees.
47 Delimited(DelimSpan, Delimiter, TokenStream),
50 // Ensure all fields of `TokenTree` is `Send` and `Sync`.
51 #[cfg(parallel_compiler)]
55 DelimSpan: Send + Sync,
56 Delimiter: Send + Sync,
57 TokenStream: Send + Sync,
62 /// Checks if this `TokenTree` is equal to the other, regardless of span information.
63 pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
65 (TokenTree::Token(token, _), TokenTree::Token(token2, _)) => token.kind == token2.kind,
66 (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
67 delim == delim2 && tts.eq_unspanned(tts2)
73 /// Retrieves the `TokenTree`'s span.
74 pub fn span(&self) -> Span {
76 TokenTree::Token(token, _) => token.span,
77 TokenTree::Delimited(sp, ..) => sp.entire(),
81 /// Modify the `TokenTree`'s span in-place.
82 pub fn set_span(&mut self, span: Span) {
84 TokenTree::Token(token, _) => token.span = span,
85 TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
89 /// Create a `TokenTree::Token` with alone spacing.
90 pub fn token_alone(kind: TokenKind, span: Span) -> TokenTree {
91 TokenTree::Token(Token::new(kind, span), Spacing::Alone)
94 /// Create a `TokenTree::Token` with joint spacing.
95 pub fn token_joint(kind: TokenKind, span: Span) -> TokenTree {
96 TokenTree::Token(Token::new(kind, span), Spacing::Joint)
99 pub fn uninterpolate(self) -> TokenTree {
101 TokenTree::Token(token, spacing) => {
102 TokenTree::Token(token.uninterpolate().into_owned(), spacing)
109 impl<CTX> HashStable<CTX> for TokenStream
111 CTX: crate::HashStableContext,
113 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
114 for sub_tt in self.trees() {
115 sub_tt.hash_stable(hcx, hasher);
120 pub trait ToAttrTokenStream: sync::Send + sync::Sync {
121 fn to_attr_token_stream(&self) -> AttrTokenStream;
124 impl ToAttrTokenStream for AttrTokenStream {
125 fn to_attr_token_stream(&self) -> AttrTokenStream {
130 /// A lazy version of [`TokenStream`], which defers creation
131 /// of an actual `TokenStream` until it is needed.
132 /// `Box` is here only to reduce the structure size.
134 pub struct LazyAttrTokenStream(Lrc<Box<dyn ToAttrTokenStream>>);
136 impl LazyAttrTokenStream {
137 pub fn new(inner: impl ToAttrTokenStream + 'static) -> LazyAttrTokenStream {
138 LazyAttrTokenStream(Lrc::new(Box::new(inner)))
141 pub fn to_attr_token_stream(&self) -> AttrTokenStream {
142 self.0.to_attr_token_stream()
146 impl fmt::Debug for LazyAttrTokenStream {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 write!(f, "LazyAttrTokenStream({:?})", self.to_attr_token_stream())
152 impl<S: Encoder> Encodable<S> for LazyAttrTokenStream {
153 fn encode(&self, s: &mut S) {
154 // Used by AST json printing.
155 Encodable::encode(&self.to_attr_token_stream(), s);
159 impl<D: Decoder> Decodable<D> for LazyAttrTokenStream {
160 fn decode(_d: &mut D) -> Self {
161 panic!("Attempted to decode LazyAttrTokenStream");
165 impl<CTX> HashStable<CTX> for LazyAttrTokenStream {
166 fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) {
167 panic!("Attempted to compute stable hash for LazyAttrTokenStream");
171 /// An `AttrTokenStream` is similar to a `TokenStream`, but with extra
172 /// information about the tokens for attribute targets. This is used
173 /// during expansion to perform early cfg-expansion, and to process attributes
174 /// during proc-macro invocations.
175 #[derive(Clone, Debug, Default, Encodable, Decodable)]
176 pub struct AttrTokenStream(pub Lrc<Vec<AttrTokenTree>>);
178 /// Like `TokenTree`, but for `AttrTokenStream`.
179 #[derive(Clone, Debug, Encodable, Decodable)]
180 pub enum AttrTokenTree {
181 Token(Token, Spacing),
182 Delimited(DelimSpan, Delimiter, AttrTokenStream),
183 /// Stores the attributes for an attribute target,
184 /// along with the tokens for that attribute target.
185 /// See `AttributesData` for more information
186 Attributes(AttributesData),
189 impl AttrTokenStream {
190 pub fn new(tokens: Vec<AttrTokenTree>) -> AttrTokenStream {
191 AttrTokenStream(Lrc::new(tokens))
194 /// Converts this `AttrTokenStream` to a plain `TokenStream`.
195 /// During conversion, `AttrTokenTree::Attributes` get 'flattened'
196 /// back to a `TokenStream` of the form `outer_attr attr_target`.
197 /// If there are inner attributes, they are inserted into the proper
198 /// place in the attribute target tokens.
199 pub fn to_tokenstream(&self) -> TokenStream {
200 let trees: Vec<_> = self
203 .flat_map(|tree| match &tree {
204 AttrTokenTree::Token(inner, spacing) => {
205 smallvec![TokenTree::Token(inner.clone(), *spacing)].into_iter()
207 AttrTokenTree::Delimited(span, delim, stream) => {
208 smallvec![TokenTree::Delimited(*span, *delim, stream.to_tokenstream()),]
211 AttrTokenTree::Attributes(data) => {
212 let mut outer_attrs = Vec::new();
213 let mut inner_attrs = Vec::new();
214 for attr in &data.attrs {
216 crate::AttrStyle::Outer => outer_attrs.push(attr),
217 crate::AttrStyle::Inner => inner_attrs.push(attr),
221 let mut target_tokens: Vec<_> = data
223 .to_attr_token_stream()
229 if !inner_attrs.is_empty() {
230 let mut found = false;
231 // Check the last two trees (to account for a trailing semi)
232 for tree in target_tokens.iter_mut().rev().take(2) {
233 if let TokenTree::Delimited(span, delim, delim_tokens) = tree {
234 // Inner attributes are only supported on extern blocks, functions,
235 // impls, and modules. All of these have their inner attributes
236 // placed at the beginning of the rightmost outermost braced group:
237 // e.g. fn foo() { #![my_attr} }
239 // Therefore, we can insert them back into the right location
240 // without needing to do any extra position tracking.
242 // Note: Outline modules are an exception - they can
243 // have attributes like `#![my_attr]` at the start of a file.
244 // Support for custom attributes in this position is not
245 // properly implemented - we always synthesize fake tokens,
246 // so we never reach this code.
248 let mut stream = TokenStream::default();
249 for inner_attr in inner_attrs {
250 stream.push_stream(inner_attr.tokens());
252 stream.push_stream(delim_tokens.clone());
253 *tree = TokenTree::Delimited(*span, *delim, stream);
261 "Failed to find trailing delimited group in: {target_tokens:?}"
264 let mut flat: SmallVec<[_; 1]> = SmallVec::new();
265 for attr in outer_attrs {
266 // FIXME: Make this more efficient
267 flat.extend(attr.tokens().0.clone().iter().cloned());
269 flat.extend(target_tokens);
274 TokenStream::new(trees)
278 /// Stores the tokens for an attribute target, along
279 /// with its attributes.
281 /// This is constructed during parsing when we need to capture
284 /// For example, `#[cfg(FALSE)] struct Foo {}` would
285 /// have an `attrs` field containing the `#[cfg(FALSE)]` attr,
286 /// and a `tokens` field storing the (unparsed) tokens `struct Foo {}`
287 #[derive(Clone, Debug, Encodable, Decodable)]
288 pub struct AttributesData {
289 /// Attributes, both outer and inner.
290 /// These are stored in the original order that they were parsed in.
292 /// The underlying tokens for the attribute target that `attrs`
294 pub tokens: LazyAttrTokenStream,
297 /// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s.
299 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
300 /// instead of a representation of the abstract syntax tree.
301 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for
302 /// backwards compatibility.
303 #[derive(Clone, Debug, Default, Encodable, Decodable)]
304 pub struct TokenStream(pub(crate) Lrc<Vec<TokenTree>>);
306 /// Similar to `proc_macro::Spacing`, but for tokens.
308 /// Note that all `ast::TokenTree::Token` instances have a `Spacing`, but when
309 /// we convert to `proc_macro::TokenTree` for proc macros only `Punct`
310 /// `TokenTree`s have a `proc_macro::Spacing`.
311 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
313 /// The token is not immediately followed by an operator token (as
314 /// determined by `Token::is_op`). E.g. a `+` token is `Alone` in `+ =`,
315 /// `+/*foo*/=`, `+ident`, and `+()`.
318 /// The token is immediately followed by an operator token. E.g. a `+`
319 /// token is `Joint` in `+=` and `++`.
324 /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
325 /// separating the two arguments with a comma for diagnostic suggestions.
326 pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
327 // Used to suggest if a user writes `foo!(a b);`
328 let mut suggestion = None;
329 let mut iter = self.0.iter().enumerate().peekable();
330 while let Some((pos, ts)) = iter.next() {
331 if let Some((_, next)) = iter.peek() {
332 let sp = match (&ts, &next) {
333 (_, TokenTree::Token(Token { kind: token::Comma, .. }, _)) => continue,
335 TokenTree::Token(token_left, Spacing::Alone),
336 TokenTree::Token(token_right, _),
337 ) if ((token_left.is_ident() && !token_left.is_reserved_ident())
338 || token_left.is_lit())
339 && ((token_right.is_ident() && !token_right.is_reserved_ident())
340 || token_right.is_lit()) =>
344 (TokenTree::Delimited(sp, ..), _) => sp.entire(),
347 let sp = sp.shrink_to_hi();
348 let comma = TokenTree::token_alone(token::Comma, sp);
349 suggestion = Some((pos, comma, sp));
352 if let Some((pos, comma, sp)) = suggestion {
353 let mut new_stream = Vec::with_capacity(self.0.len() + 1);
354 let parts = self.0.split_at(pos + 1);
355 new_stream.extend_from_slice(parts.0);
356 new_stream.push(comma);
357 new_stream.extend_from_slice(parts.1);
358 return Some((TokenStream::new(new_stream), sp));
364 impl FromIterator<TokenTree> for TokenStream {
365 fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
366 TokenStream::new(iter.into_iter().collect::<Vec<TokenTree>>())
370 impl Eq for TokenStream {}
372 impl PartialEq<TokenStream> for TokenStream {
373 fn eq(&self, other: &TokenStream) -> bool {
374 self.trees().eq(other.trees())
379 pub fn new(streams: Vec<TokenTree>) -> TokenStream {
380 TokenStream(Lrc::new(streams))
383 pub fn is_empty(&self) -> bool {
387 pub fn len(&self) -> usize {
391 pub fn trees(&self) -> CursorRef<'_> {
395 pub fn into_trees(self) -> Cursor {
399 /// Compares two `TokenStream`s, checking equality without regarding span information.
400 pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
401 let mut t1 = self.trees();
402 let mut t2 = other.trees();
403 for (t1, t2) in iter::zip(&mut t1, &mut t2) {
404 if !t1.eq_unspanned(t2) {
408 t1.next().is_none() && t2.next().is_none()
411 pub fn map_enumerated<F: FnMut(usize, &TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream {
412 TokenStream(Lrc::new(self.0.iter().enumerate().map(|(i, tree)| f(i, tree)).collect()))
415 /// Create a token stream containing a single token with alone spacing.
416 pub fn token_alone(kind: TokenKind, span: Span) -> TokenStream {
417 TokenStream::new(vec![TokenTree::token_alone(kind, span)])
420 /// Create a token stream containing a single token with joint spacing.
421 pub fn token_joint(kind: TokenKind, span: Span) -> TokenStream {
422 TokenStream::new(vec![TokenTree::token_joint(kind, span)])
425 /// Create a token stream containing a single `Delimited`.
426 pub fn delimited(span: DelimSpan, delim: Delimiter, tts: TokenStream) -> TokenStream {
427 TokenStream::new(vec![TokenTree::Delimited(span, delim, tts)])
430 pub fn from_ast(node: &(impl HasAttrs + HasSpan + HasTokens + fmt::Debug)) -> TokenStream {
431 let Some(tokens) = node.tokens() else {
432 panic!("missing tokens for node at {:?}: {:?}", node.span(), node);
434 let attrs = node.attrs();
435 let attr_stream = if attrs.is_empty() {
436 tokens.to_attr_token_stream()
439 AttributesData { attrs: attrs.iter().cloned().collect(), tokens: tokens.clone() };
440 AttrTokenStream::new(vec![AttrTokenTree::Attributes(attr_data)])
442 attr_stream.to_tokenstream()
445 pub fn from_nonterminal_ast(nt: &Nonterminal) -> TokenStream {
447 Nonterminal::NtIdent(ident, is_raw) => {
448 TokenStream::token_alone(token::Ident(ident.name, *is_raw), ident.span)
450 Nonterminal::NtLifetime(ident) => {
451 TokenStream::token_alone(token::Lifetime(ident.name), ident.span)
453 Nonterminal::NtItem(item) => TokenStream::from_ast(item),
454 Nonterminal::NtBlock(block) => TokenStream::from_ast(block),
455 Nonterminal::NtStmt(stmt) if let StmtKind::Empty = stmt.kind => {
456 // FIXME: Properly collect tokens for empty statements.
457 TokenStream::token_alone(token::Semi, stmt.span)
459 Nonterminal::NtStmt(stmt) => TokenStream::from_ast(stmt),
460 Nonterminal::NtPat(pat) => TokenStream::from_ast(pat),
461 Nonterminal::NtTy(ty) => TokenStream::from_ast(ty),
462 Nonterminal::NtMeta(attr) => TokenStream::from_ast(attr),
463 Nonterminal::NtPath(path) => TokenStream::from_ast(path),
464 Nonterminal::NtVis(vis) => TokenStream::from_ast(vis),
465 Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => TokenStream::from_ast(expr),
469 fn flatten_token(token: &Token, spacing: Spacing) -> TokenTree {
471 token::Interpolated(nt) if let token::NtIdent(ident, is_raw) = **nt => {
472 TokenTree::Token(Token::new(token::Ident(ident.name, is_raw), ident.span), spacing)
474 token::Interpolated(nt) => TokenTree::Delimited(
475 DelimSpan::from_single(token.span),
476 Delimiter::Invisible,
477 TokenStream::from_nonterminal_ast(nt).flattened(),
479 _ => TokenTree::Token(token.clone(), spacing),
483 fn flatten_token_tree(tree: &TokenTree) -> TokenTree {
485 TokenTree::Token(token, spacing) => TokenStream::flatten_token(token, *spacing),
486 TokenTree::Delimited(span, delim, tts) => {
487 TokenTree::Delimited(*span, *delim, tts.flattened())
493 pub fn flattened(&self) -> TokenStream {
494 fn can_skip(stream: &TokenStream) -> bool {
495 stream.trees().all(|tree| match tree {
496 TokenTree::Token(token, _) => !matches!(token.kind, token::Interpolated(_)),
497 TokenTree::Delimited(_, _, inner) => can_skip(inner),
505 self.trees().map(|tree| TokenStream::flatten_token_tree(tree)).collect()
508 // If `vec` is not empty, try to glue `tt` onto its last token. The return
509 // value indicates if gluing took place.
510 fn try_glue_to_last(vec: &mut Vec<TokenTree>, tt: &TokenTree) -> bool {
511 if let Some(TokenTree::Token(last_tok, Spacing::Joint)) = vec.last()
512 && let TokenTree::Token(tok, spacing) = tt
513 && let Some(glued_tok) = last_tok.glue(tok)
515 // ...then overwrite the last token tree in `vec` with the
516 // glued token, and skip the first token tree from `stream`.
517 *vec.last_mut().unwrap() = TokenTree::Token(glued_tok, *spacing);
524 /// Push `tt` onto the end of the stream, possibly gluing it to the last
525 /// token. Uses `make_mut` to maximize efficiency.
526 pub fn push_tree(&mut self, tt: TokenTree) {
527 let vec_mut = Lrc::make_mut(&mut self.0);
529 if Self::try_glue_to_last(vec_mut, &tt) {
530 // nothing else to do
536 /// Push `stream` onto the end of the stream, possibly gluing the first
537 /// token tree to the last token. (No other token trees will be glued.)
538 /// Uses `make_mut` to maximize efficiency.
539 pub fn push_stream(&mut self, stream: TokenStream) {
540 let vec_mut = Lrc::make_mut(&mut self.0);
542 let stream_iter = stream.0.iter().cloned();
544 if let Some(first) = stream.0.first() && Self::try_glue_to_last(vec_mut, first) {
545 // Now skip the first token tree from `stream`.
546 vec_mut.extend(stream_iter.skip(1));
548 // Append all of `stream`.
549 vec_mut.extend(stream_iter);
554 /// By-reference iterator over a [`TokenStream`].
556 pub struct CursorRef<'t> {
557 stream: &'t TokenStream,
561 impl<'t> CursorRef<'t> {
562 fn new(stream: &'t TokenStream) -> Self {
563 CursorRef { stream, index: 0 }
566 pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
567 self.stream.0.get(self.index + n)
571 impl<'t> Iterator for CursorRef<'t> {
572 type Item = &'t TokenTree;
574 fn next(&mut self) -> Option<&'t TokenTree> {
575 self.stream.0.get(self.index).map(|tree| {
582 /// Owning by-value iterator over a [`TokenStream`].
583 // FIXME: Many uses of this can be replaced with by-reference iterator to avoid clones.
586 pub stream: TokenStream,
590 impl Iterator for Cursor {
591 type Item = TokenTree;
593 fn next(&mut self) -> Option<TokenTree> {
594 self.stream.0.get(self.index).map(|tree| {
602 fn new(stream: TokenStream) -> Self {
603 Cursor { stream, index: 0 }
607 pub fn next_ref(&mut self) -> Option<&TokenTree> {
608 self.stream.0.get(self.index).map(|tree| {
614 pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
615 self.stream.0.get(self.index + n)
619 #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
620 pub struct DelimSpan {
626 pub fn from_single(sp: Span) -> Self {
627 DelimSpan { open: sp, close: sp }
630 pub fn from_pair(open: Span, close: Span) -> Self {
631 DelimSpan { open, close }
634 pub fn dummy() -> Self {
635 Self::from_single(DUMMY_SP)
638 pub fn entire(self) -> Span {
639 self.open.with_hi(self.close.hi())
643 // Some types are used a lot. Make sure they don't unintentionally get bigger.
644 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
647 use rustc_data_structures::static_assert_size;
648 // tidy-alphabetical-start
649 static_assert_size!(AttrTokenStream, 8);
650 static_assert_size!(AttrTokenTree, 32);
651 static_assert_size!(LazyAttrTokenStream, 8);
652 static_assert_size!(TokenStream, 8);
653 static_assert_size!(TokenTree, 32);
654 // tidy-alphabetical-end