• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! # Token Streams
2 //!
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.
6 //!
7 //! ## Ownership
8 //!
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.
15 
16 use crate::ast::StmtKind;
17 use crate::ast_traits::{HasAttrs, HasSpan, HasTokens};
18 use crate::token::{self, Delimiter, Nonterminal, Token, TokenKind};
19 use crate::AttrVec;
20 
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};
27 
28 use std::{fmt, iter, mem};
29 
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.
34 ///
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.
39 ///
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)]
43 pub enum TokenTree {
44     /// A single token. Should never be `OpenDelim` or `CloseDelim`, because
45     /// delimiters are implicitly represented by `Delimited`.
46     Token(Token, Spacing),
47     /// A delimited sequence of token trees.
48     Delimited(DelimSpan, Delimiter, TokenStream),
49 }
50 
51 // Ensure all fields of `TokenTree` are `DynSend` and `DynSync`.
52 #[cfg(parallel_compiler)]
_dummy() where Token: sync::DynSend + sync::DynSync, Spacing: sync::DynSend + sync::DynSync, DelimSpan: sync::DynSend + sync::DynSync, Delimiter: sync::DynSend + sync::DynSync, TokenStream: sync::DynSend + sync::DynSync,53 fn _dummy()
54 where
55     Token: sync::DynSend + sync::DynSync,
56     Spacing: sync::DynSend + sync::DynSync,
57     DelimSpan: sync::DynSend + sync::DynSync,
58     Delimiter: sync::DynSend + sync::DynSync,
59     TokenStream: sync::DynSend + sync::DynSync,
60 {
61 }
62 
63 impl TokenTree {
64     /// Checks if this `TokenTree` is equal to the other, regardless of span information.
eq_unspanned(&self, other: &TokenTree) -> bool65     pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
66         match (self, other) {
67             (TokenTree::Token(token, _), TokenTree::Token(token2, _)) => token.kind == token2.kind,
68             (TokenTree::Delimited(_, delim, tts), TokenTree::Delimited(_, delim2, tts2)) => {
69                 delim == delim2 && tts.eq_unspanned(tts2)
70             }
71             _ => false,
72         }
73     }
74 
75     /// Retrieves the `TokenTree`'s span.
span(&self) -> Span76     pub fn span(&self) -> Span {
77         match self {
78             TokenTree::Token(token, _) => token.span,
79             TokenTree::Delimited(sp, ..) => sp.entire(),
80         }
81     }
82 
83     /// Modify the `TokenTree`'s span in-place.
set_span(&mut self, span: Span)84     pub fn set_span(&mut self, span: Span) {
85         match self {
86             TokenTree::Token(token, _) => token.span = span,
87             TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span),
88         }
89     }
90 
91     /// Create a `TokenTree::Token` with alone spacing.
token_alone(kind: TokenKind, span: Span) -> TokenTree92     pub fn token_alone(kind: TokenKind, span: Span) -> TokenTree {
93         TokenTree::Token(Token::new(kind, span), Spacing::Alone)
94     }
95 
96     /// Create a `TokenTree::Token` with joint spacing.
token_joint(kind: TokenKind, span: Span) -> TokenTree97     pub fn token_joint(kind: TokenKind, span: Span) -> TokenTree {
98         TokenTree::Token(Token::new(kind, span), Spacing::Joint)
99     }
100 
uninterpolate(self) -> TokenTree101     pub fn uninterpolate(self) -> TokenTree {
102         match self {
103             TokenTree::Token(token, spacing) => {
104                 TokenTree::Token(token.uninterpolate().into_owned(), spacing)
105             }
106             tt => tt,
107         }
108     }
109 }
110 
111 impl<CTX> HashStable<CTX> for TokenStream
112 where
113     CTX: crate::HashStableContext,
114 {
hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher)115     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
116         for sub_tt in self.trees() {
117             sub_tt.hash_stable(hcx, hasher);
118         }
119     }
120 }
121 
122 pub trait ToAttrTokenStream: sync::DynSend + sync::DynSync {
to_attr_token_stream(&self) -> AttrTokenStream123     fn to_attr_token_stream(&self) -> AttrTokenStream;
124 }
125 
126 impl ToAttrTokenStream for AttrTokenStream {
to_attr_token_stream(&self) -> AttrTokenStream127     fn to_attr_token_stream(&self) -> AttrTokenStream {
128         self.clone()
129     }
130 }
131 
132 /// A lazy version of [`TokenStream`], which defers creation
133 /// of an actual `TokenStream` until it is needed.
134 /// `Box` is here only to reduce the structure size.
135 #[derive(Clone)]
136 pub struct LazyAttrTokenStream(Lrc<Box<dyn ToAttrTokenStream>>);
137 
138 impl LazyAttrTokenStream {
new(inner: impl ToAttrTokenStream + 'static) -> LazyAttrTokenStream139     pub fn new(inner: impl ToAttrTokenStream + 'static) -> LazyAttrTokenStream {
140         LazyAttrTokenStream(Lrc::new(Box::new(inner)))
141     }
142 
to_attr_token_stream(&self) -> AttrTokenStream143     pub fn to_attr_token_stream(&self) -> AttrTokenStream {
144         self.0.to_attr_token_stream()
145     }
146 }
147 
148 impl fmt::Debug for LazyAttrTokenStream {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result149     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150         write!(f, "LazyAttrTokenStream({:?})", self.to_attr_token_stream())
151     }
152 }
153 
154 impl<S: Encoder> Encodable<S> for LazyAttrTokenStream {
encode(&self, s: &mut S)155     fn encode(&self, s: &mut S) {
156         // Used by AST json printing.
157         Encodable::encode(&self.to_attr_token_stream(), s);
158     }
159 }
160 
161 impl<D: Decoder> Decodable<D> for LazyAttrTokenStream {
decode(_d: &mut D) -> Self162     fn decode(_d: &mut D) -> Self {
163         panic!("Attempted to decode LazyAttrTokenStream");
164     }
165 }
166 
167 impl<CTX> HashStable<CTX> for LazyAttrTokenStream {
hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher)168     fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) {
169         panic!("Attempted to compute stable hash for LazyAttrTokenStream");
170     }
171 }
172 
173 /// An `AttrTokenStream` is similar to a `TokenStream`, but with extra
174 /// information about the tokens for attribute targets. This is used
175 /// during expansion to perform early cfg-expansion, and to process attributes
176 /// during proc-macro invocations.
177 #[derive(Clone, Debug, Default, Encodable, Decodable)]
178 pub struct AttrTokenStream(pub Lrc<Vec<AttrTokenTree>>);
179 
180 /// Like `TokenTree`, but for `AttrTokenStream`.
181 #[derive(Clone, Debug, Encodable, Decodable)]
182 pub enum AttrTokenTree {
183     Token(Token, Spacing),
184     Delimited(DelimSpan, Delimiter, AttrTokenStream),
185     /// Stores the attributes for an attribute target,
186     /// along with the tokens for that attribute target.
187     /// See `AttributesData` for more information
188     Attributes(AttributesData),
189 }
190 
191 impl AttrTokenStream {
new(tokens: Vec<AttrTokenTree>) -> AttrTokenStream192     pub fn new(tokens: Vec<AttrTokenTree>) -> AttrTokenStream {
193         AttrTokenStream(Lrc::new(tokens))
194     }
195 
196     /// Converts this `AttrTokenStream` to a plain `TokenStream`.
197     /// During conversion, `AttrTokenTree::Attributes` get 'flattened'
198     /// back to a `TokenStream` of the form `outer_attr attr_target`.
199     /// If there are inner attributes, they are inserted into the proper
200     /// place in the attribute target tokens.
to_tokenstream(&self) -> TokenStream201     pub fn to_tokenstream(&self) -> TokenStream {
202         let trees: Vec<_> = self
203             .0
204             .iter()
205             .flat_map(|tree| match &tree {
206                 AttrTokenTree::Token(inner, spacing) => {
207                     smallvec![TokenTree::Token(inner.clone(), *spacing)].into_iter()
208                 }
209                 AttrTokenTree::Delimited(span, delim, stream) => {
210                     smallvec![TokenTree::Delimited(*span, *delim, stream.to_tokenstream()),]
211                         .into_iter()
212                 }
213                 AttrTokenTree::Attributes(data) => {
214                     let mut outer_attrs = Vec::new();
215                     let mut inner_attrs = Vec::new();
216                     for attr in &data.attrs {
217                         match attr.style {
218                             crate::AttrStyle::Outer => outer_attrs.push(attr),
219                             crate::AttrStyle::Inner => inner_attrs.push(attr),
220                         }
221                     }
222 
223                     let mut target_tokens: Vec<_> = data
224                         .tokens
225                         .to_attr_token_stream()
226                         .to_tokenstream()
227                         .0
228                         .iter()
229                         .cloned()
230                         .collect();
231                     if !inner_attrs.is_empty() {
232                         let mut found = false;
233                         // Check the last two trees (to account for a trailing semi)
234                         for tree in target_tokens.iter_mut().rev().take(2) {
235                             if let TokenTree::Delimited(span, delim, delim_tokens) = tree {
236                                 // Inner attributes are only supported on extern blocks, functions,
237                                 // impls, and modules. All of these have their inner attributes
238                                 // placed at the beginning of the rightmost outermost braced group:
239                                 // e.g. fn foo() { #![my_attr} }
240                                 //
241                                 // Therefore, we can insert them back into the right location
242                                 // without needing to do any extra position tracking.
243                                 //
244                                 // Note: Outline modules are an exception - they can
245                                 // have attributes like `#![my_attr]` at the start of a file.
246                                 // Support for custom attributes in this position is not
247                                 // properly implemented - we always synthesize fake tokens,
248                                 // so we never reach this code.
249 
250                                 let mut stream = TokenStream::default();
251                                 for inner_attr in inner_attrs {
252                                     stream.push_stream(inner_attr.tokens());
253                                 }
254                                 stream.push_stream(delim_tokens.clone());
255                                 *tree = TokenTree::Delimited(*span, *delim, stream);
256                                 found = true;
257                                 break;
258                             }
259                         }
260 
261                         assert!(
262                             found,
263                             "Failed to find trailing delimited group in: {target_tokens:?}"
264                         );
265                     }
266                     let mut flat: SmallVec<[_; 1]> = SmallVec::new();
267                     for attr in outer_attrs {
268                         // FIXME: Make this more efficient
269                         flat.extend(attr.tokens().0.clone().iter().cloned());
270                     }
271                     flat.extend(target_tokens);
272                     flat.into_iter()
273                 }
274             })
275             .collect();
276         TokenStream::new(trees)
277     }
278 }
279 
280 /// Stores the tokens for an attribute target, along
281 /// with its attributes.
282 ///
283 /// This is constructed during parsing when we need to capture
284 /// tokens.
285 ///
286 /// For example, `#[cfg(FALSE)] struct Foo {}` would
287 /// have an `attrs` field containing the `#[cfg(FALSE)]` attr,
288 /// and a `tokens` field storing the (unparsed) tokens `struct Foo {}`
289 #[derive(Clone, Debug, Encodable, Decodable)]
290 pub struct AttributesData {
291     /// Attributes, both outer and inner.
292     /// These are stored in the original order that they were parsed in.
293     pub attrs: AttrVec,
294     /// The underlying tokens for the attribute target that `attrs`
295     /// are applied to
296     pub tokens: LazyAttrTokenStream,
297 }
298 
299 /// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s.
300 ///
301 /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s
302 /// instead of a representation of the abstract syntax tree.
303 /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for
304 /// backwards compatibility.
305 #[derive(Clone, Debug, Default, Encodable, Decodable)]
306 pub struct TokenStream(pub(crate) Lrc<Vec<TokenTree>>);
307 
308 /// Similar to `proc_macro::Spacing`, but for tokens.
309 ///
310 /// Note that all `ast::TokenTree::Token` instances have a `Spacing`, but when
311 /// we convert to `proc_macro::TokenTree` for proc macros only `Punct`
312 /// `TokenTree`s have a `proc_macro::Spacing`.
313 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
314 pub enum Spacing {
315     /// The token is not immediately followed by an operator token (as
316     /// determined by `Token::is_op`). E.g. a `+` token is `Alone` in `+ =`,
317     /// `+/*foo*/=`, `+ident`, and `+()`.
318     Alone,
319 
320     /// The token is immediately followed by an operator token. E.g. a `+`
321     /// token is `Joint` in `+=` and `++`.
322     Joint,
323 }
324 
325 impl TokenStream {
326     /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
327     /// separating the two arguments with a comma for diagnostic suggestions.
add_comma(&self) -> Option<(TokenStream, Span)>328     pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
329         // Used to suggest if a user writes `foo!(a b);`
330         let mut suggestion = None;
331         let mut iter = self.0.iter().enumerate().peekable();
332         while let Some((pos, ts)) = iter.next() {
333             if let Some((_, next)) = iter.peek() {
334                 let sp = match (&ts, &next) {
335                     (_, TokenTree::Token(Token { kind: token::Comma, .. }, _)) => continue,
336                     (
337                         TokenTree::Token(token_left, Spacing::Alone),
338                         TokenTree::Token(token_right, _),
339                     ) if ((token_left.is_ident() && !token_left.is_reserved_ident())
340                         || token_left.is_lit())
341                         && ((token_right.is_ident() && !token_right.is_reserved_ident())
342                             || token_right.is_lit()) =>
343                     {
344                         token_left.span
345                     }
346                     (TokenTree::Delimited(sp, ..), _) => sp.entire(),
347                     _ => continue,
348                 };
349                 let sp = sp.shrink_to_hi();
350                 let comma = TokenTree::token_alone(token::Comma, sp);
351                 suggestion = Some((pos, comma, sp));
352             }
353         }
354         if let Some((pos, comma, sp)) = suggestion {
355             let mut new_stream = Vec::with_capacity(self.0.len() + 1);
356             let parts = self.0.split_at(pos + 1);
357             new_stream.extend_from_slice(parts.0);
358             new_stream.push(comma);
359             new_stream.extend_from_slice(parts.1);
360             return Some((TokenStream::new(new_stream), sp));
361         }
362         None
363     }
364 }
365 
366 impl FromIterator<TokenTree> for TokenStream {
from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self367     fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
368         TokenStream::new(iter.into_iter().collect::<Vec<TokenTree>>())
369     }
370 }
371 
372 impl Eq for TokenStream {}
373 
374 impl PartialEq<TokenStream> for TokenStream {
eq(&self, other: &TokenStream) -> bool375     fn eq(&self, other: &TokenStream) -> bool {
376         self.trees().eq(other.trees())
377     }
378 }
379 
380 impl TokenStream {
new(streams: Vec<TokenTree>) -> TokenStream381     pub fn new(streams: Vec<TokenTree>) -> TokenStream {
382         TokenStream(Lrc::new(streams))
383     }
384 
is_empty(&self) -> bool385     pub fn is_empty(&self) -> bool {
386         self.0.is_empty()
387     }
388 
len(&self) -> usize389     pub fn len(&self) -> usize {
390         self.0.len()
391     }
392 
trees(&self) -> RefTokenTreeCursor<'_>393     pub fn trees(&self) -> RefTokenTreeCursor<'_> {
394         RefTokenTreeCursor::new(self)
395     }
396 
into_trees(self) -> TokenTreeCursor397     pub fn into_trees(self) -> TokenTreeCursor {
398         TokenTreeCursor::new(self)
399     }
400 
401     /// Compares two `TokenStream`s, checking equality without regarding span information.
eq_unspanned(&self, other: &TokenStream) -> bool402     pub fn eq_unspanned(&self, other: &TokenStream) -> bool {
403         let mut t1 = self.trees();
404         let mut t2 = other.trees();
405         for (t1, t2) in iter::zip(&mut t1, &mut t2) {
406             if !t1.eq_unspanned(t2) {
407                 return false;
408             }
409         }
410         t1.next().is_none() && t2.next().is_none()
411     }
412 
413     /// Applies the supplied function to each `TokenTree` and its index in `self`, returning a new `TokenStream`
414     ///
415     /// It is equivalent to `TokenStream::new(self.trees().cloned().enumerate().map(|(i, tt)| f(i, tt)).collect())`.
map_enumerated_owned( mut self, mut f: impl FnMut(usize, TokenTree) -> TokenTree, ) -> TokenStream416     pub fn map_enumerated_owned(
417         mut self,
418         mut f: impl FnMut(usize, TokenTree) -> TokenTree,
419     ) -> TokenStream {
420         let owned = Lrc::make_mut(&mut self.0); // clone if necessary
421         // rely on vec's in-place optimizations to avoid another allocation
422         *owned = mem::take(owned).into_iter().enumerate().map(|(i, tree)| f(i, tree)).collect();
423         self
424     }
425 
426     /// Create a token stream containing a single token with alone spacing.
token_alone(kind: TokenKind, span: Span) -> TokenStream427     pub fn token_alone(kind: TokenKind, span: Span) -> TokenStream {
428         TokenStream::new(vec![TokenTree::token_alone(kind, span)])
429     }
430 
431     /// Create a token stream containing a single token with joint spacing.
token_joint(kind: TokenKind, span: Span) -> TokenStream432     pub fn token_joint(kind: TokenKind, span: Span) -> TokenStream {
433         TokenStream::new(vec![TokenTree::token_joint(kind, span)])
434     }
435 
436     /// Create a token stream containing a single `Delimited`.
delimited(span: DelimSpan, delim: Delimiter, tts: TokenStream) -> TokenStream437     pub fn delimited(span: DelimSpan, delim: Delimiter, tts: TokenStream) -> TokenStream {
438         TokenStream::new(vec![TokenTree::Delimited(span, delim, tts)])
439     }
440 
from_ast(node: &(impl HasAttrs + HasSpan + HasTokens + fmt::Debug)) -> TokenStream441     pub fn from_ast(node: &(impl HasAttrs + HasSpan + HasTokens + fmt::Debug)) -> TokenStream {
442         let Some(tokens) = node.tokens() else {
443             panic!("missing tokens for node at {:?}: {:?}", node.span(), node);
444         };
445         let attrs = node.attrs();
446         let attr_stream = if attrs.is_empty() {
447             tokens.to_attr_token_stream()
448         } else {
449             let attr_data =
450                 AttributesData { attrs: attrs.iter().cloned().collect(), tokens: tokens.clone() };
451             AttrTokenStream::new(vec![AttrTokenTree::Attributes(attr_data)])
452         };
453         attr_stream.to_tokenstream()
454     }
455 
from_nonterminal_ast(nt: &Nonterminal) -> TokenStream456     pub fn from_nonterminal_ast(nt: &Nonterminal) -> TokenStream {
457         match nt {
458             Nonterminal::NtIdent(ident, is_raw) => {
459                 TokenStream::token_alone(token::Ident(ident.name, *is_raw), ident.span)
460             }
461             Nonterminal::NtLifetime(ident) => {
462                 TokenStream::token_alone(token::Lifetime(ident.name), ident.span)
463             }
464             Nonterminal::NtItem(item) => TokenStream::from_ast(item),
465             Nonterminal::NtBlock(block) => TokenStream::from_ast(block),
466             Nonterminal::NtStmt(stmt) if let StmtKind::Empty = stmt.kind => {
467                 // FIXME: Properly collect tokens for empty statements.
468                 TokenStream::token_alone(token::Semi, stmt.span)
469             }
470             Nonterminal::NtStmt(stmt) => TokenStream::from_ast(stmt),
471             Nonterminal::NtPat(pat) => TokenStream::from_ast(pat),
472             Nonterminal::NtTy(ty) => TokenStream::from_ast(ty),
473             Nonterminal::NtMeta(attr) => TokenStream::from_ast(attr),
474             Nonterminal::NtPath(path) => TokenStream::from_ast(path),
475             Nonterminal::NtVis(vis) => TokenStream::from_ast(vis),
476             Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => TokenStream::from_ast(expr),
477         }
478     }
479 
flatten_token(token: &Token, spacing: Spacing) -> TokenTree480     fn flatten_token(token: &Token, spacing: Spacing) -> TokenTree {
481         match &token.kind {
482             token::Interpolated(nt) if let token::NtIdent(ident, is_raw) = **nt => {
483                 TokenTree::Token(Token::new(token::Ident(ident.name, is_raw), ident.span), spacing)
484             }
485             token::Interpolated(nt) => TokenTree::Delimited(
486                 DelimSpan::from_single(token.span),
487                 Delimiter::Invisible,
488                 TokenStream::from_nonterminal_ast(nt).flattened(),
489             ),
490             _ => TokenTree::Token(token.clone(), spacing),
491         }
492     }
493 
flatten_token_tree(tree: &TokenTree) -> TokenTree494     fn flatten_token_tree(tree: &TokenTree) -> TokenTree {
495         match tree {
496             TokenTree::Token(token, spacing) => TokenStream::flatten_token(token, *spacing),
497             TokenTree::Delimited(span, delim, tts) => {
498                 TokenTree::Delimited(*span, *delim, tts.flattened())
499             }
500         }
501     }
502 
503     #[must_use]
flattened(&self) -> TokenStream504     pub fn flattened(&self) -> TokenStream {
505         fn can_skip(stream: &TokenStream) -> bool {
506             stream.trees().all(|tree| match tree {
507                 TokenTree::Token(token, _) => !matches!(token.kind, token::Interpolated(_)),
508                 TokenTree::Delimited(_, _, inner) => can_skip(inner),
509             })
510         }
511 
512         if can_skip(self) {
513             return self.clone();
514         }
515 
516         self.trees().map(|tree| TokenStream::flatten_token_tree(tree)).collect()
517     }
518 
519     // If `vec` is not empty, try to glue `tt` onto its last token. The return
520     // value indicates if gluing took place.
try_glue_to_last(vec: &mut Vec<TokenTree>, tt: &TokenTree) -> bool521     fn try_glue_to_last(vec: &mut Vec<TokenTree>, tt: &TokenTree) -> bool {
522         if let Some(TokenTree::Token(last_tok, Spacing::Joint)) = vec.last()
523             && let TokenTree::Token(tok, spacing) = tt
524             && let Some(glued_tok) = last_tok.glue(tok)
525         {
526             // ...then overwrite the last token tree in `vec` with the
527             // glued token, and skip the first token tree from `stream`.
528             *vec.last_mut().unwrap() = TokenTree::Token(glued_tok, *spacing);
529             true
530         } else {
531             false
532         }
533     }
534 
535     /// Push `tt` onto the end of the stream, possibly gluing it to the last
536     /// token. Uses `make_mut` to maximize efficiency.
push_tree(&mut self, tt: TokenTree)537     pub fn push_tree(&mut self, tt: TokenTree) {
538         let vec_mut = Lrc::make_mut(&mut self.0);
539 
540         if Self::try_glue_to_last(vec_mut, &tt) {
541             // nothing else to do
542         } else {
543             vec_mut.push(tt);
544         }
545     }
546 
547     /// Push `stream` onto the end of the stream, possibly gluing the first
548     /// token tree to the last token. (No other token trees will be glued.)
549     /// Uses `make_mut` to maximize efficiency.
push_stream(&mut self, stream: TokenStream)550     pub fn push_stream(&mut self, stream: TokenStream) {
551         let vec_mut = Lrc::make_mut(&mut self.0);
552 
553         let stream_iter = stream.0.iter().cloned();
554 
555         if let Some(first) = stream.0.first() && Self::try_glue_to_last(vec_mut, first) {
556             // Now skip the first token tree from `stream`.
557             vec_mut.extend(stream_iter.skip(1));
558         } else {
559             // Append all of `stream`.
560             vec_mut.extend(stream_iter);
561         }
562     }
563 
chunks(&self, chunk_size: usize) -> core::slice::Chunks<'_, TokenTree>564     pub fn chunks(&self, chunk_size: usize) -> core::slice::Chunks<'_, TokenTree> {
565         self.0.chunks(chunk_size)
566     }
567 }
568 
569 /// By-reference iterator over a [`TokenStream`], that produces `&TokenTree`
570 /// items.
571 #[derive(Clone)]
572 pub struct RefTokenTreeCursor<'t> {
573     stream: &'t TokenStream,
574     index: usize,
575 }
576 
577 impl<'t> RefTokenTreeCursor<'t> {
new(stream: &'t TokenStream) -> Self578     fn new(stream: &'t TokenStream) -> Self {
579         RefTokenTreeCursor { stream, index: 0 }
580     }
581 
look_ahead(&self, n: usize) -> Option<&TokenTree>582     pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
583         self.stream.0.get(self.index + n)
584     }
585 }
586 
587 impl<'t> Iterator for RefTokenTreeCursor<'t> {
588     type Item = &'t TokenTree;
589 
next(&mut self) -> Option<&'t TokenTree>590     fn next(&mut self) -> Option<&'t TokenTree> {
591         self.stream.0.get(self.index).map(|tree| {
592             self.index += 1;
593             tree
594         })
595     }
596 }
597 
598 /// Owning by-value iterator over a [`TokenStream`], that produces `TokenTree`
599 /// items.
600 // FIXME: Many uses of this can be replaced with by-reference iterator to avoid clones.
601 #[derive(Clone)]
602 pub struct TokenTreeCursor {
603     pub stream: TokenStream,
604     index: usize,
605 }
606 
607 impl Iterator for TokenTreeCursor {
608     type Item = TokenTree;
609 
next(&mut self) -> Option<TokenTree>610     fn next(&mut self) -> Option<TokenTree> {
611         self.stream.0.get(self.index).map(|tree| {
612             self.index += 1;
613             tree.clone()
614         })
615     }
616 }
617 
618 impl TokenTreeCursor {
new(stream: TokenStream) -> Self619     fn new(stream: TokenStream) -> Self {
620         TokenTreeCursor { stream, index: 0 }
621     }
622 
623     #[inline]
next_ref(&mut self) -> Option<&TokenTree>624     pub fn next_ref(&mut self) -> Option<&TokenTree> {
625         self.stream.0.get(self.index).map(|tree| {
626             self.index += 1;
627             tree
628         })
629     }
630 
look_ahead(&self, n: usize) -> Option<&TokenTree>631     pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
632         self.stream.0.get(self.index + n)
633     }
634 
635     // Replace the previously obtained token tree with `tts`, and rewind to
636     // just before them.
replace_prev_and_rewind(&mut self, tts: Vec<TokenTree>)637     pub fn replace_prev_and_rewind(&mut self, tts: Vec<TokenTree>) {
638         assert!(self.index > 0);
639         self.index -= 1;
640         let stream = Lrc::make_mut(&mut self.stream.0);
641         stream.splice(self.index..self.index + 1, tts);
642     }
643 }
644 
645 #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
646 pub struct DelimSpan {
647     pub open: Span,
648     pub close: Span,
649 }
650 
651 impl DelimSpan {
from_single(sp: Span) -> Self652     pub fn from_single(sp: Span) -> Self {
653         DelimSpan { open: sp, close: sp }
654     }
655 
from_pair(open: Span, close: Span) -> Self656     pub fn from_pair(open: Span, close: Span) -> Self {
657         DelimSpan { open, close }
658     }
659 
dummy() -> Self660     pub fn dummy() -> Self {
661         Self::from_single(DUMMY_SP)
662     }
663 
entire(self) -> Span664     pub fn entire(self) -> Span {
665         self.open.with_hi(self.close.hi())
666     }
667 }
668 
669 // Some types are used a lot. Make sure they don't unintentionally get bigger.
670 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
671 mod size_asserts {
672     use super::*;
673     use rustc_data_structures::static_assert_size;
674     // tidy-alphabetical-start
675     static_assert_size!(AttrTokenStream, 8);
676     static_assert_size!(AttrTokenTree, 32);
677     static_assert_size!(LazyAttrTokenStream, 8);
678     static_assert_size!(TokenStream, 8);
679     static_assert_size!(TokenTree, 32);
680     // tidy-alphabetical-end
681 }
682