Skip to main content

rustc_ast/
tokenstream.rs

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
7use std::borrow::Cow;
8use std::hash::Hash;
9use std::ops::Range;
10use std::sync::{Arc, LazyLock};
11use std::{cmp, fmt, iter, mem};
12
13use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
14use rustc_data_structures::sync;
15use rustc_macros::{Decodable, Encodable, StableHash, Walkable};
16use rustc_serialize::{Decodable, Encodable};
17use rustc_span::{DUMMY_SP, Span, SpanDecoder, SpanEncoder, Symbol, sym};
18use thin_vec::ThinVec;
19
20use crate::ast::AttrStyle;
21use crate::ast_traits::HasTokens;
22use crate::token::{self, Delimiter, Token, TokenKind};
23use crate::{AttrVec, Attribute};
24
25#[cfg(test)]
26mod tests;
27
28/// Part of a `TokenStream`.
29#[derive(#[automatically_derived]impl ::core::fmt::Debug for TokenTree {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Token(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "Token",
                    __self_0, &__self_1),
            Self::Delimited(__self_0, __self_1, __self_2, __self_3) =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "Delimited", __self_0, __self_1, __self_2, &__self_3),
        }
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for TokenTree {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Token(__self_0, __self_1) =>
                TokenTree::Token(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            Self::Delimited(__self_0, __self_1, __self_2, __self_3) =>
                TokenTree::Delimited(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1),
                    ::core::clone::Clone::clone(__self_2),
                    ::core::clone::Clone::clone(__self_3)),
        }
    }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for TokenTree
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TokenTree {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Token(__self_0, __self_1),
                    Self::Token(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (Self::Delimited(__self_0, __self_1, __self_2, __self_3),
                    Self::Delimited(__arg1_0, __arg1_1, __arg1_2, __arg1_3)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1 &&
                            __self_2 == __arg1_2 && __self_3 == __arg1_3,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for TokenTree {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Token>;
        let _: ::core::cmp::AssertParamIsEq<Spacing>;
        let _: ::core::cmp::AssertParamIsEq<DelimSpan>;
        let _: ::core::cmp::AssertParamIsEq<DelimSpacing>;
        let _: ::core::cmp::AssertParamIsEq<Delimiter>;
        let _: ::core::cmp::AssertParamIsEq<TokenStream>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for TokenTree {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state);
        match self {
            Self::Token(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            Self::Delimited(__self_0, __self_1, __self_2, __self_3) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state);
                ::core::hash::Hash::hash(__self_2, state);
                ::core::hash::Hash::hash(__self_3, state)
            }
        }
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for TokenTree {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        TokenTree::Token(ref __binding_0, ref __binding_1) => {
                            0usize
                        }
                        TokenTree::Delimited(ref __binding_0, ref __binding_1,
                            ref __binding_2, ref __binding_3) => {
                            1usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    TokenTree::Token(ref __binding_0, ref __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    TokenTree::Delimited(ref __binding_0, ref __binding_1,
                        ref __binding_2, ref __binding_3) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_3,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for TokenTree {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        TokenTree::Token(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        TokenTree::Delimited(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `TokenTree`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for TokenTree {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    TokenTree::Token(ref __binding_0, ref __binding_1) =>
                        0u8.stable_hash(__hcx, __hasher),
                    TokenTree::Delimited(ref __binding_0, ref __binding_1,
                        ref __binding_2, ref __binding_3) =>
                        1u8.stable_hash(__hcx, __hasher),
                }
                match *self {
                    TokenTree::Token(ref __binding_0, ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    TokenTree::Delimited(ref __binding_0, ref __binding_1,
                        ref __binding_2, ref __binding_3) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
30pub enum TokenTree {
31    /// A single token. Should never be `OpenDelim` or `CloseDelim`, because
32    /// delimiters are implicitly represented by `Delimited`.
33    Token(Token, Spacing),
34    /// A delimited sequence of token trees.
35    Delimited(DelimSpan, DelimSpacing, Delimiter, TokenStream),
36}
37
38// Ensure all fields of `TokenTree` are `DynSend` and `DynSync`.
39fn _dummy()
40where
41    Token: sync::DynSend + sync::DynSync,
42    Spacing: sync::DynSend + sync::DynSync,
43    DelimSpan: sync::DynSend + sync::DynSync,
44    Delimiter: sync::DynSend + sync::DynSync,
45    TokenStream: sync::DynSend + sync::DynSync,
46{
47}
48
49impl TokenTree {
50    /// Checks if this `TokenTree` is equal to the other, regardless of span/spacing information.
51    pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
52        match (self, other) {
53            (TokenTree::Token(token, _), TokenTree::Token(token2, _)) => token.kind == token2.kind,
54            (TokenTree::Delimited(.., delim, tts), TokenTree::Delimited(.., delim2, tts2)) => {
55                delim == delim2 && tts.iter().eq_by(tts2.iter(), |a, b| a.eq_unspanned(b))
56            }
57            _ => false,
58        }
59    }
60
61    /// Retrieves the `TokenTree`'s span.
62    pub fn span(&self) -> Span {
63        match self {
64            TokenTree::Token(token, _) => token.span,
65            TokenTree::Delimited(sp, ..) => sp.entire(),
66        }
67    }
68
69    /// Create a `TokenTree::Token` with alone spacing.
70    pub fn token_alone(kind: TokenKind, span: Span) -> TokenTree {
71        TokenTree::Token(Token::new(kind, span), Spacing::Alone)
72    }
73
74    /// Create a `TokenTree::Token` with joint spacing.
75    pub fn token_joint(kind: TokenKind, span: Span) -> TokenTree {
76        TokenTree::Token(Token::new(kind, span), Spacing::Joint)
77    }
78
79    /// Create a `TokenTree::Token` with joint-hidden spacing.
80    pub fn token_joint_hidden(kind: TokenKind, span: Span) -> TokenTree {
81        TokenTree::Token(Token::new(kind, span), Spacing::JointHidden)
82    }
83
84    pub fn uninterpolate(&self) -> Cow<'_, TokenTree> {
85        match self {
86            TokenTree::Token(token, spacing) => match token.uninterpolate() {
87                Cow::Owned(token) => Cow::Owned(TokenTree::Token(token, *spacing)),
88                Cow::Borrowed(_) => Cow::Borrowed(self),
89            },
90            _ => Cow::Borrowed(self),
91        }
92    }
93}
94
95#[derive(#[automatically_derived]impl<T: ::core::clone::Clone> ::core::clone::Clone for
    WithTokens<T> {
    #[inline]
    fn clone(&self) -> Self {
        WithTokens {
            node: ::core::clone::Clone::clone(&self.node),
            tokens: ::core::clone::Clone::clone(&self.tokens),
        }
    }
}Clone, #[automatically_derived]impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
    WithTokens<T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "WithTokens node tokens", &self.node, &&self.tokens)
    }
}Debug)]
96pub struct WithTokens<T> {
97    pub node: T,
98    pub tokens: Option<LazyTokenStream>,
99}
100
101impl<T> WithTokens<T> {
102    pub fn new(node: T) -> WithTokens<T> {
103        WithTokens { node, tokens: None }
104    }
105
106    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> WithTokens<U> {
107        WithTokens { node: f(self.node), tokens: self.tokens }
108    }
109}
110
111/// A lazy version of [`TokenStream`], which defers creation of an actual `TokenStream` until it is
112/// needed.
113#[derive(#[automatically_derived]impl ::core::clone::Clone for LazyTokenStream {
    #[inline]
    fn clone(&self) -> Self {
        LazyTokenStream(::core::clone::Clone::clone(&self.0))
    }
}Clone)]
114pub struct LazyTokenStream(Arc<LazyTokenStreamInner>);
115
116impl LazyTokenStream {
117    pub fn new_direct(stream: TokenStream) -> LazyTokenStream {
118        LazyTokenStream(Arc::new(LazyTokenStreamInner::Direct(stream)))
119    }
120
121    pub fn new_pending(
122        start_token: (Token, Spacing),
123        cursor_snapshot: TokenCursor,
124        num_calls: u32,
125        break_last_token: u32,
126        node_replacements: ThinVec<NodeReplacement>,
127    ) -> LazyTokenStream {
128        LazyTokenStream(Arc::new(LazyTokenStreamInner::Pending {
129            start_token,
130            cursor_snapshot,
131            num_calls,
132            break_last_token,
133            node_replacements,
134        }))
135    }
136
137    pub fn to_token_stream(&self) -> TokenStream {
138        self.0.to_configured_token_stream(&mut keep_all)
139    }
140
141    pub fn to_configured_token_stream(&self, configure: &mut ConfigureFn<'_>) -> TokenStream {
142        self.0.to_configured_token_stream(configure)
143    }
144
145    pub fn append_token_trees_to(&self, res: &mut Vec<TokenTree>) {
146        self.0.append_token_trees_to(&mut keep_all, res);
147    }
148}
149
150impl fmt::Debug for LazyTokenStream {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        f.write_fmt(format_args!("LazyTokenStream({0:?})", self.to_token_stream()))write!(f, "LazyTokenStream({:?})", self.to_token_stream())
153    }
154}
155
156impl<S: SpanEncoder> Encodable<S> for LazyTokenStream {
157    fn encode(&self, _s: &mut S) {
158        {
    ::core::panicking::panic_fmt(format_args!("Attempted to encode LazyTokenStream"));
};panic!("Attempted to encode LazyTokenStream");
159    }
160}
161
162impl<D: SpanDecoder> Decodable<D> for LazyTokenStream {
163    fn decode(_d: &mut D) -> Self {
164        {
    ::core::panicking::panic_fmt(format_args!("Attempted to decode LazyTokenStream"));
};panic!("Attempted to decode LazyTokenStream");
165    }
166}
167
168impl StableHash for LazyTokenStream {
169    fn stable_hash<Hcx: StableHashCtxt>(&self, _hcx: &mut Hcx, _hasher: &mut StableHasher) {
170        {
    ::core::panicking::panic_fmt(format_args!("Attempted to compute stable hash for LazyTokenStream"));
};panic!("Attempted to compute stable hash for LazyTokenStream");
171    }
172}
173
174/// A token range within a `Parser`'s full token stream.
175#[derive(#[automatically_derived]impl ::core::clone::Clone for ParserRange {
    #[inline]
    fn clone(&self) -> Self {
        ParserRange(::core::clone::Clone::clone(&self.0))
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for ParserRange {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "ParserRange",
            &&self.0)
    }
}Debug)]
176pub struct ParserRange(pub Range<u32>);
177
178/// A token range within an individual AST node's (lazy) token stream, i.e.
179/// relative to that node's first token. Distinct from `ParserRange` so the two
180/// kinds of range can't be mixed up.
181#[derive(#[automatically_derived]impl ::core::clone::Clone for NodeRange {
    #[inline]
    fn clone(&self) -> Self {
        NodeRange(::core::clone::Clone::clone(&self.0))
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for NodeRange {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "NodeRange",
            &&self.0)
    }
}Debug)]
182pub struct NodeRange(pub Range<u32>);
183
184/// Indicates a range of tokens that should be replaced by an `AttrsTarget`
185/// (replacement) or be replaced by nothing (deletion). This is used in two
186/// places during token collection.
187///
188/// 1. Replacement. During the parsing of an AST node that may have a
189///    `#[derive]` attribute, when we parse a nested AST node that has `#[cfg]`
190///    or `#[cfg_attr]`, we replace the entire inner AST node with
191///    `FlatToken::AttrsTarget`. This lets us perform eager cfg-expansion.
192///
193/// 2. Deletion. We delete inner attributes from all collected token streams,
194///    and instead track them through the `attrs` field on the AST node. This
195///    lets us manipulate them similarly to outer attributes. When we create a
196///    `TokenStream`, the inner attributes are inserted into the proper place
197///    in the token stream.
198///
199/// Each replacement starts off in `ParserReplacement` form but is converted to
200/// `NodeReplacement` form when it is attached to a single AST node, via
201/// `LazyTokenStream`.
202pub type ParserReplacement = (ParserRange, Option<AttrsTarget>);
203
204/// See the comment on `ParserReplacement`.
205pub type NodeReplacement = (NodeRange, Option<AttrsTarget>);
206
207impl NodeRange {
208    // Converts a range within a parser's tokens to a range within a
209    // node's tokens beginning at `start_pos`.
210    //
211    // For example, imagine a parser with 50 tokens in its token stream, a
212    // function that spans `ParserRange(20..40)` and an inner attribute within
213    // that function that spans `ParserRange(30..35)`. We would find the inner
214    // attribute's range within the function's tokens by subtracting 20, which
215    // is the position of the function's start token. This gives
216    // `NodeRange(10..15)`.
217    pub fn new(ParserRange(parser_range): ParserRange, start_pos: u32) -> NodeRange {
218        if !!parser_range.is_empty() {
    ::core::panicking::panic("assertion failed: !parser_range.is_empty()")
};assert!(!parser_range.is_empty());
219        if !(parser_range.start >= start_pos) {
    ::core::panicking::panic("assertion failed: parser_range.start >= start_pos")
};assert!(parser_range.start >= start_pos);
220        NodeRange((parser_range.start - start_pos)..(parser_range.end - start_pos))
221    }
222}
223
224enum LazyTokenStreamInner {
225    // The token stream has already been produced.
226    Direct(TokenStream),
227
228    // From a value of this type we can reconstruct the `TokenStream` seen by
229    // the `f` callback passed to a call to `Parser::collect_tokens`, by
230    // replaying the getting of the tokens. This saves us producing a
231    // `TokenStream` if it is never needed, e.g. a captured `macro_rules!`
232    // argument that is never passed to a proc macro. In practice, token stream
233    // creation happens rarely compared to calls to `collect_tokens` (see some
234    // statistics in #78736) so we are doing as little up-front work as
235    // possible.
236    //
237    // This also makes `Parser` very cheap to clone, since there is no
238    // intermediate collection buffer to clone.
239    Pending {
240        start_token: (Token, Spacing),
241        cursor_snapshot: TokenCursor,
242        num_calls: u32,
243        break_last_token: u32,
244        node_replacements: ThinVec<NodeReplacement>,
245    },
246}
247
248/// Fn type used to do (or not do) `cfg` expansion. It can modify attributes. The return value
249/// indicates if the target should be retained. Any children of discarded targets are skipped.
250type ConfigureFn<'a> = dyn FnMut(&mut AttrsTarget) -> bool + 'a;
251
252/// A `ConfigureFn` that keeps the target, i.e. the node and its tokens.
253fn keep_all(_: &mut AttrsTarget) -> bool {
254    true
255}
256
257impl LazyTokenStreamInner {
258    fn to_configured_token_stream(&self, configure: &mut ConfigureFn<'_>) -> TokenStream {
259        match self {
260            LazyTokenStreamInner::Direct(stream) => stream.clone(),
261            LazyTokenStreamInner::Pending { .. } => {
262                let mut res = ::alloc::vec::Vec::new()vec![];
263                self.append_token_trees_to(configure, &mut res);
264                TokenStream::new(res)
265            }
266        }
267    }
268
269    fn append_token_trees_to(&self, configure: &mut ConfigureFn<'_>, res: &mut Vec<TokenTree>) {
270        match self {
271            LazyTokenStreamInner::Direct(stream) => res.extend(stream.iter().cloned()),
272            LazyTokenStreamInner::Pending {
273                start_token,
274                cursor_snapshot,
275                num_calls,
276                break_last_token,
277                node_replacements,
278            } => {
279                // The token produced by the final call to `{,inlined_}next_and_bump` was not
280                // actually consumed by the callback. The combination of chaining the
281                // initial token and using `take` produces the desired result - we
282                // produce an empty `TokenStream` if no calls were made, and omit the
283                // final token otherwise.
284                let mut cursor_snapshot = cursor_snapshot.clone();
285                let tokens = iter::once(FlatToken::Token(*start_token))
286                    .chain(iter::repeat_with(|| FlatToken::Token(cursor_snapshot.next_and_bump())))
287                    .take(*num_calls as usize);
288                if node_replacements.is_empty() {
289                    append_flat_tokens_as_token_trees_to(tokens, *break_last_token, configure, res);
290                } else {
291                    let mut tokens: Vec<_> = tokens.collect();
292                    let mut node_replacements = node_replacements.to_vec();
293                    node_replacements.sort_by_key(|(range, _)| range.0.start);
294
295                    #[cfg(debug_assertions)]
296                    for [(node_range, tokens), (next_node_range, next_tokens)] in
297                        node_replacements.array_windows()
298                    {
299                        if !(node_range.0.end <= next_node_range.0.start ||
            node_range.0.end >= next_node_range.0.end) {
    {
        ::core::panicking::panic_fmt(format_args!("Node ranges should be disjoint or nested: ({0:?}, {1:?}) ({2:?}, {3:?})",
                node_range, tokens, next_node_range, next_tokens));
    }
};assert!(
300                            node_range.0.end <= next_node_range.0.start
301                                || node_range.0.end >= next_node_range.0.end,
302                            "Node ranges should be disjoint or nested: ({:?}, {:?}) ({:?}, {:?})",
303                            node_range,
304                            tokens,
305                            next_node_range,
306                            next_tokens,
307                        );
308                    }
309
310                    // Process the replace ranges, starting from the highest start
311                    // position and working our way back. If have tokens like:
312                    //
313                    // `#[cfg(FALSE)] struct Foo { #[cfg(FALSE)] field: bool }`
314                    //
315                    // Then we will generate replace ranges for both
316                    // the `#[cfg(FALSE)] field: bool` and the entire
317                    // `#[cfg(FALSE)] struct Foo { #[cfg(FALSE)] field: bool }`
318                    //
319                    // By starting processing from the replace range with the greatest
320                    // start position, we ensure that any (outer) replace range which
321                    // encloses another (inner) replace range will fully overwrite the
322                    // inner range's replacement.
323                    for (node_range, target) in node_replacements.into_iter().rev() {
324                        if !!node_range.0.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("Cannot replace an empty node range: {0:?}",
                node_range.0));
    }
};assert!(
325                            !node_range.0.is_empty(),
326                            "Cannot replace an empty node range: {:?}",
327                            node_range.0
328                        );
329
330                        // Replace the tokens in range with zero or one `FlatToken::AttrsTarget`s,
331                        // plus enough `FlatToken::Empty`s to fill up the rest of the range. This
332                        // keeps the total length of `tokens` constant throughout the replacement
333                        // process, allowing us to do all replacements without adjusting indices.
334                        let target_len = target.is_some() as usize;
335                        tokens.splice(
336                            (node_range.0.start as usize)..(node_range.0.end as usize),
337                            target.into_iter().map(|target| FlatToken::AttrsTarget(target)).chain(
338                                iter::repeat(FlatToken::Empty)
339                                    .take(node_range.0.len() - target_len),
340                            ),
341                        );
342                    }
343                    append_flat_tokens_as_token_trees_to(
344                        tokens.into_iter(),
345                        *break_last_token,
346                        configure,
347                        res,
348                    );
349                }
350            }
351        }
352    }
353}
354
355/// A helper struct used when building a `TokenStream` from
356/// a `LazyTokenStream`. Both delimiter and non-delimited tokens
357/// are stored as `FlatToken::Token`. A vector of `FlatToken`s
358/// is then 'parsed' to build up a `TokenStream` with nested
359/// `TokenTree::Delimited` tokens.
360#[derive(#[automatically_derived]impl ::core::fmt::Debug for FlatToken {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Token(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Token",
                    &__self_0),
            Self::AttrsTarget(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "AttrsTarget", &__self_0),
            Self::Empty => ::core::fmt::Formatter::write_str(f, "Empty"),
        }
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for FlatToken {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Token(__self_0) =>
                FlatToken::Token(::core::clone::Clone::clone(__self_0)),
            Self::AttrsTarget(__self_0) =>
                FlatToken::AttrsTarget(::core::clone::Clone::clone(__self_0)),
            Self::Empty => FlatToken::Empty,
        }
    }
}Clone)]
361enum FlatToken {
362    /// A token. Holds both delimiter (e.g. '{' and '}') and non-delimiter tokens.
363    Token((Token, Spacing)),
364    /// Holds the `AttrsTarget` for an AST node. The `AttrsTarget` is expanded directly into the
365    /// constructed `TokenStream`.
366    AttrsTarget(AttrsTarget),
367    /// A special 'empty' token that is ignored during the conversion to a `TokenStream`. This is
368    /// used to simplify the handling of replace ranges.
369    Empty,
370}
371
372/// Converts a flattened iterator of tokens (including open and close delimiter tokens) into a
373/// sequence of `TokenTree` (appended to `res`), creating a `TokenTree::Delimited` for each
374/// matching pair of open and close delims. Any `FlatToken::AttrsTarget` element will only be
375/// appended if `configure` succeeds, and `configure` can also modify any such element.
376fn append_flat_tokens_as_token_trees_to(
377    iter: impl Iterator<Item = FlatToken>,
378    break_last_token: u32,
379    configure: &mut ConfigureFn<'_>,
380    res: &mut Vec<TokenTree>,
381) {
382    #[derive(#[automatically_derived]impl ::core::fmt::Debug for FrameData {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "FrameData open_delim_sp inner", &self.open_delim_sp,
            &&self.inner)
    }
}Debug)]
383    struct FrameData {
384        // This is `None` for the first frame, `Some` for all others.
385        open_delim_sp: Option<(Delimiter, Span, Spacing)>,
386        inner: Vec<TokenTree>,
387    }
388
389    // The stack always has at least one element. Storing it separately makes for shorter code.
390    let mut stack_top = FrameData { open_delim_sp: None, inner: mem::take(res) };
391    let mut stack_rest = ::alloc::vec::Vec::new()vec![];
392    for flat_token in iter {
393        match flat_token {
394            FlatToken::Token((token @ Token { kind, span }, spacing)) => {
395                if let Some(delim) = kind.open_delim() {
396                    stack_rest.push(mem::replace(
397                        &mut stack_top,
398                        FrameData { open_delim_sp: Some((delim, span, spacing)), inner: ::alloc::vec::Vec::new()vec![] },
399                    ));
400                } else if let Some(delim) = kind.close_delim() {
401                    // If there's no matching opening delimiter, the token stream is malformed,
402                    // likely due to an improper delimiter position in the source code. It's not
403                    // delimiter mismatch, and lexer can not detect it, so we just ignore it here.
404                    let Some(frame) = stack_rest.pop() else {
405                        *res = stack_top.inner;
406                        return;
407                    };
408                    let frame_data = mem::replace(&mut stack_top, frame);
409                    let (open_delim, open_sp, open_spacing) = frame_data.open_delim_sp.unwrap();
410                    if !open_delim.eq_ignoring_invisible_origin(&delim) {
    {
        ::core::panicking::panic_fmt(format_args!("Mismatched open/close delims: open={0:?} close={1:?}",
                open_delim, span));
    }
};assert!(
411                        open_delim.eq_ignoring_invisible_origin(&delim),
412                        "Mismatched open/close delims: open={open_delim:?} close={span:?}"
413                    );
414                    let dspan = DelimSpan::from_pair(open_sp, span);
415                    let dspacing = DelimSpacing::new(open_spacing, spacing);
416                    let stream = TokenStream::new(frame_data.inner);
417                    let delimited = TokenTree::Delimited(dspan, dspacing, delim, stream);
418                    stack_top.inner.push(delimited);
419                } else {
420                    stack_top.inner.push(TokenTree::Token(token, spacing))
421                }
422            }
423            FlatToken::AttrsTarget(mut target) => {
424                if configure(&mut target) {
425                    append_attrs_and_stream_as_token_trees_to(
426                        &target.attrs,
427                        &target.tokens,
428                        configure,
429                        &mut stack_top.inner,
430                    );
431                }
432            }
433            FlatToken::Empty => {}
434        }
435    }
436
437    if break_last_token > 0 {
438        let last_token = stack_top.inner.pop().unwrap();
439        if let TokenTree::Token(last_token, spacing) = last_token {
440            let (unglued, _) = last_token.kind.break_two_token_op(break_last_token).unwrap();
441
442            // Tokens are always ASCII chars, so we can use byte arithmetic here.
443            let mut first_span = last_token.span.shrink_to_lo();
444            first_span =
445                first_span.with_hi(first_span.lo() + rustc_span::BytePos(break_last_token));
446
447            stack_top.inner.push(TokenTree::Token(Token::new(unglued, first_span), spacing));
448        } else {
449            {
    ::core::panicking::panic_fmt(format_args!("Unexpected last token {0:?}",
            last_token));
}panic!("Unexpected last token {last_token:?}")
450        }
451    }
452
453    *res = stack_top.inner;
454}
455
456// Converts multiple attributes and the tokens for a target AST node into token trees, and appends
457// them to `res`.
458//
459// Example: if the AST node is "fn f() { blah(); }", then:
460// - Simple if no attributes are present, e.g. "fn f() { blah(); }"
461// - Simple if only outer attribute are present, e.g. "#[outer1] #[outer2] fn f() { blah(); }"
462// - Trickier if inner attributes are present, because they must be moved within the AST node's
463//   tokens, e.g. "#[outer] fn f() { #![inner] blah() }"
464fn append_attrs_and_stream_as_token_trees_to(
465    attrs: &[Attribute],
466    target_tokens: &LazyTokenStream,
467    configure: &mut ConfigureFn<'_>,
468    res: &mut Vec<TokenTree>,
469) {
470    let idx = attrs.partition_point(|attr| #[allow(non_exhaustive_omitted_patterns)] match attr.style {
    crate::AttrStyle::Outer => true,
    _ => false,
}matches!(attr.style, crate::AttrStyle::Outer));
471    let (outer_attrs, inner_attrs) = attrs.split_at(idx);
472
473    // Add outer attribute tokens.
474    for attr in outer_attrs {
475        attr.append_token_trees_to(res);
476    }
477
478    // Add target AST node tokens.
479    target_tokens.0.append_token_trees_to(configure, res);
480
481    // Insert inner attribute tokens.
482    if !inner_attrs.is_empty() {
483        let found = insert_inner_attrs(inner_attrs, res);
484        if !found {
    {
        ::core::panicking::panic_fmt(format_args!("Failed to find trailing delimited group in: {0:?}",
                res));
    }
};assert!(found, "Failed to find trailing delimited group in: {res:?}");
485    }
486
487    // Inner attributes are only supported on blocks, functions, impls, and
488    // modules. All of these have their inner attributes placed at the
489    // beginning of the rightmost outermost braced group:
490    // e.g. `fn foo() { #![my_attr] }`. (Note: the braces may be within
491    // invisible delimiters.)
492    //
493    // Therefore, we can insert them back into the right location without
494    // needing to do any extra position tracking.
495    //
496    // Note: Outline modules are an exception - they can have attributes like
497    // `#![my_attr]` at the start of a file. Support for custom attributes in
498    // this position is not properly implemented - we always synthesize fake
499    // tokens, so we never reach this code.
500    fn insert_inner_attrs(inner_attrs: &[Attribute], tts: &mut Vec<TokenTree>) -> bool {
501        for tree in tts.iter_mut().rev() {
502            if let TokenTree::Delimited(span, spacing, Delimiter::Brace, stream) = tree {
503                // Found it: the rightmost, outermost braced group.
504                let mut tts = ::alloc::vec::Vec::new()vec![];
505                for inner_attr in inner_attrs {
506                    inner_attr.append_token_trees_to(&mut tts);
507                }
508                tts.extend(stream.0.iter().cloned());
509                let stream = TokenStream::new(tts);
510                *tree = TokenTree::Delimited(*span, *spacing, Delimiter::Brace, stream);
511                return true;
512            } else if let TokenTree::Delimited(span, spacing, Delimiter::Invisible(src), stream) =
513                tree
514            {
515                // Recurse inside invisible delimiters.
516                let mut vec: Vec<_> = stream.iter().cloned().collect();
517                if insert_inner_attrs(inner_attrs, &mut vec) {
518                    *tree = TokenTree::Delimited(
519                        *span,
520                        *spacing,
521                        Delimiter::Invisible(*src),
522                        TokenStream::new(vec),
523                    );
524                    return true;
525                }
526            }
527        }
528        false
529    }
530}
531
532/// Stores the tokens for an attribute target, along
533/// with its attributes.
534///
535/// This is constructed during parsing when we need to capture
536/// tokens, for `cfg` and `cfg_attr` attributes.
537///
538/// For example, `#[cfg(FALSE)] struct Foo {}` would
539/// have an `attrs` field containing the `#[cfg(FALSE)]` attr,
540/// and a `tokens` field storing the (unparsed) tokens `struct Foo {}`
541///
542/// The `cfg`/`cfg_attr` processing occurs in
543/// `StripUnconfigured::try_configure_tokens`.
544#[derive(#[automatically_derived]impl ::core::clone::Clone for AttrsTarget {
    #[inline]
    fn clone(&self) -> Self {
        AttrsTarget {
            attrs: ::core::clone::Clone::clone(&self.attrs),
            tokens: ::core::clone::Clone::clone(&self.tokens),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for AttrsTarget {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "AttrsTarget attrs tokens", &self.attrs, &&self.tokens)
    }
}Debug)]
545pub struct AttrsTarget {
546    /// Attributes, both outer and inner.
547    /// These are stored in the original order that they were parsed in.
548    pub attrs: AttrVec,
549    /// The underlying tokens for the attribute target that `attrs`
550    /// are applied to
551    pub tokens: LazyTokenStream,
552}
553
554/// Indicates whether a token can join with the following token to form a
555/// compound token. Used for conversions to `proc_macro::Spacing`. Also used to
556/// guide pretty-printing, which is where the `JointHidden` value (which isn't
557/// part of `proc_macro::Spacing`) comes in useful.
558#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Spacing {
}
#[automatically_derived]impl ::core::clone::Clone for Spacing {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Spacing { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Spacing {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Spacing::Alone => "Alone",
                Spacing::Joint => "Joint",
                Spacing::JointHidden => "JointHidden",
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Spacing {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Spacing {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Spacing { }Eq, #[automatically_derived]impl ::core::hash::Hash for Spacing {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Spacing {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        Spacing::Alone => { 0usize }
                        Spacing::Joint => { 1usize }
                        Spacing::JointHidden => { 2usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for Spacing {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { Spacing::Alone }
                    1usize => { Spacing::Joint }
                    2usize => { Spacing::JointHidden }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Spacing`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for Spacing {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Spacing::Alone => 0u8.stable_hash(__hcx, __hasher),
                    Spacing::Joint => 1u8.stable_hash(__hcx, __hasher),
                    Spacing::JointHidden => 2u8.stable_hash(__hcx, __hasher),
                }
                match *self {
                    Spacing::Alone => {}
                    Spacing::Joint => {}
                    Spacing::JointHidden => {}
                }
            }
        }
    };StableHash)]
559pub enum Spacing {
560    /// The token cannot join with the following token to form a compound
561    /// token.
562    ///
563    /// In token streams parsed from source code, the compiler will use `Alone`
564    /// for any token immediately followed by whitespace, a non-doc comment, or
565    /// EOF.
566    ///
567    /// When constructing token streams within the compiler, use this for each
568    /// token that (a) should be pretty-printed with a space after it, or (b)
569    /// is the last token in the stream. (In the latter case the choice of
570    /// spacing doesn't matter because it is never used for the last token. We
571    /// arbitrarily use `Alone`.)
572    ///
573    /// Converts to `proc_macro::Spacing::Alone`, and
574    /// `proc_macro::Spacing::Alone` converts back to this.
575    Alone,
576
577    /// The token can join with the following token to form a compound token.
578    ///
579    /// In token streams parsed from source code, the compiler will use `Joint`
580    /// for any token immediately followed by punctuation (as determined by
581    /// `Token::is_punct`).
582    ///
583    /// When constructing token streams within the compiler, use this for each
584    /// token that (a) should be pretty-printed without a space after it, and
585    /// (b) is followed by a punctuation token.
586    ///
587    /// Converts to `proc_macro::Spacing::Joint`, and
588    /// `proc_macro::Spacing::Joint` converts back to this.
589    Joint,
590
591    /// The token can join with the following token to form a compound token,
592    /// but this will not be visible at the proc macro level. (This is what the
593    /// `Hidden` means; see below.)
594    ///
595    /// In token streams parsed from source code, the compiler will use
596    /// `JointHidden` for any token immediately followed by anything not
597    /// covered by the `Alone` and `Joint` cases: an identifier, lifetime,
598    /// literal, delimiter, doc comment.
599    ///
600    /// When constructing token streams, use this for each token that (a)
601    /// should be pretty-printed without a space after it, and (b) is followed
602    /// by a non-punctuation token.
603    ///
604    /// Converts to `proc_macro::Spacing::Alone`, but
605    /// `proc_macro::Spacing::Alone` converts back to `token::Spacing::Alone`.
606    /// Because of that, pretty-printing of `TokenStream`s produced by proc
607    /// macros is unavoidably uglier (with more whitespace between tokens) than
608    /// pretty-printing of `TokenStream`'s produced by other means (i.e. parsed
609    /// source code, internally constructed token streams, and token streams
610    /// produced by declarative macros).
611    JointHidden,
612}
613
614/// A shared empty token stream, used to avoid an unnecessary `Arc` allocation for every empty
615/// token stream.
616static EMPTY_TOKEN_STREAM: LazyLock<TokenStream> =
617    LazyLock::new(|| TokenStream(Arc::new(Vec::new())));
618
619/// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s.
620#[derive(#[automatically_derived]impl ::core::clone::Clone for TokenStream {
    #[inline]
    fn clone(&self) -> Self {
        TokenStream(::core::clone::Clone::clone(&self.0))
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for TokenStream {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "TokenStream",
            &&self.0)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    TokenStream {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TokenStream {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for TokenStream {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Arc<Vec<TokenTree>>>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for TokenStream {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for TokenStream {
            fn encode(&self, __encoder: &mut __E) {
                let TokenStream(ref __binding_0) = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for TokenStream {
            fn decode(__decoder: &mut __D) -> Self {
                TokenStream(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };Decodable)]
621pub struct TokenStream(Arc<Vec<TokenTree>>);
622
623impl TokenStream {
624    pub fn new(tts: Vec<TokenTree>) -> TokenStream {
625        if tts.is_empty() { TokenStream::default() } else { TokenStream(Arc::new(tts)) }
626    }
627
628    pub fn is_empty(&self) -> bool {
629        self.0.is_empty()
630    }
631
632    pub fn len(&self) -> usize {
633        self.0.len()
634    }
635
636    pub fn get(&self, index: usize) -> Option<&TokenTree> {
637        self.0.get(index)
638    }
639
640    pub fn iter(&self) -> TokenStreamIter<'_> {
641        TokenStreamIter::new(self)
642    }
643
644    /// Create a token stream containing a single token with alone spacing. The
645    /// spacing used for the final token in a constructed stream doesn't matter
646    /// because it's never used. In practice we arbitrarily use
647    /// `Spacing::Alone`.
648    pub fn token_alone(kind: TokenKind, span: Span) -> TokenStream {
649        TokenStream::new(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [TokenTree::token_alone(kind, span)]))vec![TokenTree::token_alone(kind, span)])
650    }
651
652    pub fn from_ast(node: &(impl HasTokens + fmt::Debug)) -> TokenStream {
653        let tokens = node.tokens().unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("missing tokens for node: {0:?}",
            node));
}panic!("missing tokens for node: {:?}", node));
654        let mut tts = ::alloc::vec::Vec::new()vec![];
655        append_attrs_and_stream_as_token_trees_to(node.attrs(), tokens, &mut keep_all, &mut tts);
656        TokenStream::new(tts)
657    }
658
659    // If `vec` is not empty, try to glue `tt` onto its last token. The return
660    // value indicates if gluing took place.
661    fn try_glue_to_last(vec: &mut [TokenTree], tt: &TokenTree) -> bool {
662        if let Some(TokenTree::Token(last_tok, Spacing::Joint | Spacing::JointHidden)) = vec.last()
663            && let TokenTree::Token(tok, spacing) = tt
664            && let Some(glued_tok) = last_tok.glue(tok)
665        {
666            // ...then overwrite the last token tree in `vec` with the glued token.
667            *vec.last_mut().unwrap() = TokenTree::Token(glued_tok, *spacing);
668            true
669        } else {
670            false
671        }
672    }
673
674    /// Push `tt` onto the end of the stream, possibly gluing it to the last
675    /// token. Uses `make_mut` to maximize efficiency.
676    ///
677    /// This is intended for specific proc macro use. For general `TokenStream`
678    /// construction within the compiler just build a `Vec<TokenTree>` with
679    /// normal `Vec` operations and then do `TokenStream::new`.
680    pub fn push_tree_with_gluing(&mut self, tt: TokenTree) {
681        let vec_mut = Arc::make_mut(&mut self.0);
682
683        if Self::try_glue_to_last(vec_mut, &tt) {
684            // nothing else to do
685        } else {
686            vec_mut.push(tt);
687        }
688    }
689
690    /// Push `stream` onto the end of the stream, possibly gluing the first
691    /// token tree to the last token. (No other token trees will be glued.)
692    /// Uses `make_mut` to maximize efficiency.
693    ///
694    /// This is intended for specific proc macro use. For general `TokenStream`
695    /// construction within the compiler just build a `Vec<TokenTree>` with
696    /// normal `Vec` operations and then do `TokenStream::new`.
697    pub fn push_stream_with_gluing(&mut self, stream: TokenStream) {
698        let vec_mut = Arc::make_mut(&mut self.0);
699
700        let stream_iter = stream.0.iter().cloned();
701
702        if let Some(first) = stream.0.first()
703            && Self::try_glue_to_last(vec_mut, first)
704        {
705            // Now skip the first token tree from `stream`.
706            vec_mut.extend(stream_iter.skip(1));
707        } else {
708            // Append all of `stream`.
709            vec_mut.extend(stream_iter);
710        }
711    }
712
713    /// Desugar doc comments like `/// foo` in the stream into `#[doc =
714    /// r"foo"]`. Modifies the `TokenStream` via `Arc::make_mut`, but as little
715    /// as possible.
716    pub fn desugar_doc_comments(&mut self) {
717        if let Some(desugared_stream) = desugar_inner(self.clone()) {
718            *self = desugared_stream;
719        }
720
721        // The return value is `None` if nothing in `stream` changed.
722        fn desugar_inner(mut stream: TokenStream) -> Option<TokenStream> {
723            let mut i = 0;
724            let mut modified = false;
725            while let Some(tt) = stream.0.get(i) {
726                match tt {
727                    &TokenTree::Token(
728                        Token { kind: token::DocComment(_, attr_style, data), span },
729                        _spacing,
730                    ) => {
731                        let desugared = desugared_tts(attr_style, data, span);
732                        let desugared_len = desugared.len();
733                        Arc::make_mut(&mut stream.0).splice(i..i + 1, desugared);
734                        modified = true;
735                        i += desugared_len;
736                    }
737
738                    &TokenTree::Token(..) => i += 1,
739
740                    &TokenTree::Delimited(sp, spacing, delim, ref delim_stream) => {
741                        if let Some(desugared_delim_stream) = desugar_inner(delim_stream.clone()) {
742                            let new_tt =
743                                TokenTree::Delimited(sp, spacing, delim, desugared_delim_stream);
744                            Arc::make_mut(&mut stream.0)[i] = new_tt;
745                            modified = true;
746                        }
747                        i += 1;
748                    }
749                }
750            }
751            if modified { Some(stream) } else { None }
752        }
753
754        fn desugared_tts(attr_style: AttrStyle, data: Symbol, span: Span) -> Vec<TokenTree> {
755            // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
756            // required to wrap the text. E.g.
757            // - `abc d` is wrapped as `r"abc d"` (num_of_hashes = 0)
758            // - `abc "d"` is wrapped as `r#"abc "d""#` (num_of_hashes = 1)
759            // - `abc "##d##"` is wrapped as `r###"abc ##"d"##"###` (num_of_hashes = 3)
760            let mut num_of_hashes = 0;
761            let mut count = 0;
762            for ch in data.as_str().chars() {
763                count = match ch {
764                    '"' => 1,
765                    '#' if count > 0 => count + 1,
766                    _ => 0,
767                };
768                num_of_hashes = cmp::max(num_of_hashes, count);
769            }
770
771            // `/// foo` becomes `[doc = r"foo"]`.
772            let delim_span = DelimSpan::from_single(span);
773            let body = TokenTree::Delimited(
774                delim_span,
775                DelimSpacing::new(Spacing::JointHidden, Spacing::Alone),
776                Delimiter::Bracket,
777                [
778                    TokenTree::token_alone(token::Ident(sym::doc, token::IdentKind::Normal), span),
779                    TokenTree::token_alone(token::Eq, span),
780                    TokenTree::token_alone(
781                        TokenKind::lit(token::StrRaw(num_of_hashes), data, None),
782                        span,
783                    ),
784                ]
785                .into_iter()
786                .collect::<TokenStream>(),
787            );
788
789            if attr_style == AttrStyle::Inner {
790                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [TokenTree::token_joint(token::Pound, span),
                TokenTree::token_joint_hidden(token::Bang, span), body]))vec![
791                    TokenTree::token_joint(token::Pound, span),
792                    TokenTree::token_joint_hidden(token::Bang, span),
793                    body,
794                ]
795            } else {
796                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [TokenTree::token_joint_hidden(token::Pound, span), body]))vec![TokenTree::token_joint_hidden(token::Pound, span), body]
797            }
798        }
799    }
800
801    /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream`
802    /// separating the two arguments with a comma for diagnostic suggestions.
803    pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
804        // Used to suggest if a user writes `foo!(a b);`
805        let mut suggestion = None;
806        let mut iter = self.0.iter().enumerate().peekable();
807        while let Some((pos, ts)) = iter.next() {
808            if let Some((_, next)) = iter.peek() {
809                let sp = match (&ts, &next) {
810                    (_, TokenTree::Token(Token { kind: token::Comma, .. }, _)) => continue,
811                    (
812                        TokenTree::Token(token_left, Spacing::Alone),
813                        TokenTree::Token(token_right, _),
814                    ) if (token_left.is_non_reserved_ident() || token_left.is_lit())
815                        && (token_right.is_non_reserved_ident() || token_right.is_lit()) =>
816                    {
817                        token_left.span
818                    }
819                    (TokenTree::Delimited(sp, ..), _) => sp.entire(),
820                    _ => continue,
821                };
822                let sp = sp.shrink_to_hi();
823                let comma = TokenTree::token_alone(token::Comma, sp);
824                suggestion = Some((pos, comma, sp));
825            }
826        }
827        if let Some((pos, comma, sp)) = suggestion {
828            let mut new_stream = Vec::with_capacity(self.0.len() + 1);
829            let parts = self.0.split_at(pos + 1);
830            new_stream.extend_from_slice(parts.0);
831            new_stream.push(comma);
832            new_stream.extend_from_slice(parts.1);
833            return Some((TokenStream::new(new_stream), sp));
834        }
835        None
836    }
837}
838
839impl Default for TokenStream {
840    fn default() -> TokenStream {
841        EMPTY_TOKEN_STREAM.clone()
842    }
843}
844
845impl FromIterator<TokenTree> for TokenStream {
846    fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
847        TokenStream::new(iter.into_iter().collect::<Vec<TokenTree>>())
848    }
849}
850
851impl StableHash for TokenStream {
852    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
853        self.0.as_slice().stable_hash(hcx, hasher);
854    }
855}
856
857#[derive(#[automatically_derived]impl<'t> ::core::clone::Clone for TokenStreamIter<'t>
    {
    #[inline]
    fn clone(&self) -> Self {
        TokenStreamIter(::core::clone::Clone::clone(&self.0))
    }
}Clone)]
858pub struct TokenStreamIter<'t>(std::slice::Iter<'t, TokenTree>);
859
860impl<'t> TokenStreamIter<'t> {
861    fn new(stream: &'t TokenStream) -> Self {
862        TokenStreamIter(stream.0.as_slice().iter())
863    }
864
865    // Peeking could be done via `Peekable`, but most iterators need peeking,
866    // and this is simple and avoids the need to use `peekable` and `Peekable`
867    // at all the use sites.
868    pub fn peek(&self) -> Option<&'t TokenTree> {
869        self.0.as_slice().first()
870    }
871}
872
873impl<'t> Iterator for TokenStreamIter<'t> {
874    type Item = &'t TokenTree;
875
876    fn next(&mut self) -> Option<&'t TokenTree> {
877        self.0.next()
878    }
879
880    fn size_hint(&self) -> (usize, Option<usize>) {
881        self.0.size_hint()
882    }
883}
884
885#[derive(#[automatically_derived]impl ::core::clone::Clone for TokenTreeCursor {
    #[inline]
    fn clone(&self) -> Self {
        TokenTreeCursor {
            stream: ::core::clone::Clone::clone(&self.stream),
            next_idx: ::core::clone::Clone::clone(&self.next_idx),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for TokenTreeCursor {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "TokenTreeCursor stream next_idx", &self.stream, &&self.next_idx)
    }
}Debug)]
886struct TokenTreeCursor {
887    stream: TokenStream,
888    /// Points to the next token tree (or one past the end of the stream).
889    next_idx: usize,
890}
891
892impl TokenTreeCursor {
893    #[inline]
894    fn new(stream: TokenStream) -> Self {
895        TokenTreeCursor { stream, next_idx: 0 }
896    }
897
898    /// Gets the current token tree within this cursor. In a debug build it panics on a cursor that
899    /// hasn't been bumped; in a release build it will return `None`.
900    #[inline]
901    fn curr(&self) -> Option<&TokenTree> {
902        if true {
    if !(self.next_idx > 0) {
        ::core::panicking::panic("assertion failed: self.next_idx > 0")
    };
};debug_assert!(self.next_idx > 0);
903        self.stream.get(self.next_idx - 1)
904    }
905
906    /// Gets the next token tree without advancing.
907    #[inline]
908    fn next(&self) -> Option<&TokenTree> {
909        self.stream.get(self.next_idx)
910    }
911
912    /// Gets the token tree `n` ahead. `look_ahead(1)` is equivalent to `next()`. `look_ahead(0)`
913    /// isn't allowed and will panic.
914    #[inline]
915    fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
916        {
    match (&n, &0) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_ne!(n, 0);
917        self.stream.get(self.next_idx + (n - 1))
918    }
919
920    /// Move the cursor to the next token tree.
921    #[inline]
922    fn bump(&mut self) {
923        self.next_idx += 1;
924    }
925
926    /// For skipping ahead in rare circumstances.
927    #[inline]
928    fn bump_to_end(&mut self) {
929        self.next_idx = self.stream.len();
930    }
931}
932
933/// A `TokenStream` cursor that produces `Token`s. It's a bit odd that
934/// we (a) lex tokens into a nice tree structure (`TokenStream`), and then (b)
935/// use this type to emit them as a linear sequence. But a linear sequence is
936/// what the parser expects, for the most part.
937#[derive(#[automatically_derived]impl ::core::clone::Clone for TokenCursor {
    #[inline]
    fn clone(&self) -> Self {
        TokenCursor {
            curr: ::core::clone::Clone::clone(&self.curr),
            stack: ::core::clone::Clone::clone(&self.stack),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for TokenCursor {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "TokenCursor curr stack", &self.curr, &&self.stack)
    }
}Debug)]
938pub struct TokenCursor {
939    // Cursor for the current (innermost) token stream. The `next_idx` within the
940    // cursor can point to any token tree in the stream (or one past the end).
941    // The delimiters for this token stream are found in the current token tree
942    // in `self.stack.last()`; if that is `None` we are in the outermost token
943    // stream which never has delimiters.
944    curr: TokenTreeCursor,
945
946    // Token streams surrounding the current one. The `next_idx` within each cursor
947    // is always greater than zero and always points one past the current
948    // `TokenTree::Delimited`.
949    stack: Vec<TokenTreeCursor>,
950}
951
952impl TokenCursor {
953    #[inline]
954    pub fn new(stream: TokenStream) -> Self {
955        TokenCursor { curr: TokenTreeCursor::new(stream), stack: ::alloc::vec::Vec::new()vec![] }
956    }
957
958    /// Gets the next token and advances the cursor by one.
959    pub fn next_and_bump(&mut self) -> (Token, Spacing) {
960        self.inlined_next_and_bump()
961    }
962
963    /// An `n` of 1 is the next token tree in the current token stream; won't look outside the
964    /// current token stream. `look_ahead(0)` isn't allowed and will panic.
965    #[inline]
966    pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
967        self.curr.look_ahead(n)
968    }
969
970    /// Returns the first token tree (if there is one) past the close delimiter of the enclosing
971    /// delimited sequence. Panics if we are not within a delimited sequence.
972    #[inline]
973    pub fn look_ahead_past_close_delim(&self) -> Option<&TokenTree> {
974        self.stack.last().unwrap().next()
975    }
976
977    /// Clones the `TokenTree::Delimited` that we are currently within. Panics if we are not within
978    /// a delimited sequence.
979    #[inline]
980    pub fn clone_enclosing_delim(&self) -> TokenTree {
981        self.stack.last().unwrap().curr().unwrap().clone()
982    }
983
984    /// For skipping to the end of the current sequence, in rare circumstances.
985    #[inline]
986    pub fn bump_to_end(&mut self) {
987        self.curr.bump_to_end()
988    }
989
990    /// Note: the outermost stream has depth of 0.
991    #[inline]
992    pub fn depth(&self) -> usize {
993        self.stack.len()
994    }
995
996    /// Returns details about the parent delimited sequence, if there is one.
997    #[inline]
998    pub fn parent_delim_and_span(&self) -> Option<(Delimiter, DelimSpan)> {
999        if let Some(last) = self.stack.last()
1000            && let Some(TokenTree::Delimited(span, _, delim, _)) = last.curr()
1001        {
1002            Some((*delim, *span))
1003        } else {
1004            None
1005        }
1006    }
1007
1008    /// This always-inlined version should only be used on hot code paths.
1009    #[inline(always)]
1010    pub fn inlined_next_and_bump(&mut self) -> (Token, Spacing) {
1011        loop {
1012            // FIXME: we currently don't return `Delimiter::Invisible` open/close delims. To fix
1013            // #67062 we will need to, whereupon the `delim != Delimiter::Invisible` conditions
1014            // below can be removed.
1015            if let Some(tree) = self.curr.next() {
1016                match tree {
1017                    &TokenTree::Token(token, spacing) => {
1018                        if true {
    if !!token.kind.is_delim() {
        ::core::panicking::panic("assertion failed: !token.kind.is_delim()")
    };
};debug_assert!(!token.kind.is_delim());
1019                        let res = (token, spacing);
1020                        self.curr.bump();
1021                        return res;
1022                    }
1023                    &TokenTree::Delimited(sp, spacing, delim, ref tts) => {
1024                        let trees = TokenTreeCursor::new(tts.clone());
1025                        self.curr.bump(); // move past the `Delimited`
1026                        self.stack.push(mem::replace(&mut self.curr, trees));
1027                        if !delim.skip() {
1028                            return (Token::new(delim.as_open_token_kind(), sp.open), spacing.open);
1029                        }
1030                        // No open delimiter to return; continue on to the next iteration.
1031                    }
1032                };
1033            } else if let Some(parent) = self.stack.pop() {
1034                // We have exhausted this token stream. Move back to its parent token stream.
1035                let Some(&TokenTree::Delimited(span, spacing, delim, _)) = parent.curr() else {
1036                    { ::core::panicking::panic_fmt(format_args!("parent should be Delimited")); }panic!("parent should be Delimited")
1037                };
1038                self.curr = parent;
1039                if !delim.skip() {
1040                    return (Token::new(delim.as_close_token_kind(), span.close), spacing.close);
1041                }
1042                // No close delimiter to return; continue on to the next iteration.
1043            } else {
1044                // We have exhausted the outermost token stream. The use of
1045                // `Spacing::Alone` is arbitrary and immaterial, because the
1046                // `Eof` token's spacing is never used.
1047                return (Token::new(token::Eof, DUMMY_SP), Spacing::Alone);
1048            }
1049        }
1050    }
1051}
1052
1053#[derive(#[automatically_derived]impl ::core::fmt::Debug for DelimSpan {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "DelimSpan open close", &self.open, &&self.close)
    }
}Debug, #[automatically_derived]impl ::core::marker::Copy for DelimSpan { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DelimSpan {
}
#[automatically_derived]impl ::core::clone::Clone for DelimSpan {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for DelimSpan
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for DelimSpan {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.open == other.open && self.close == other.close
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for DelimSpan {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Span>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for DelimSpan {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.open, state);
        ::core::hash::Hash::hash(&self.close, state)
    }
}Hash)]
1054#[derive(const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DelimSpan {
            fn encode(&self, __encoder: &mut __E) {
                let DelimSpan { open: ref __binding_0, close: ref __binding_1
                        } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for DelimSpan {
            fn decode(__decoder: &mut __D) -> Self {
                DelimSpan {
                    open: ::rustc_serialize::Decodable::decode(__decoder),
                    close: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for DelimSpan {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    DelimSpan { open: ref __binding_0, close: ref __binding_1 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'__ast, __V> crate::visit::Walkable<'__ast, __V> for DelimSpan
            where __V: crate::visit::Visitor<'__ast> {
            fn walk_ref(&'__ast self, __visitor: &mut __V) -> __V::Result {
                match *self {
                    DelimSpan { open: ref __binding_0, close: ref __binding_1 }
                        => {
                        {
                            match ::rustc_ast_ir::visit::VisitorResult::branch(crate::visit::Visitable::visit(__binding_0,
                                        __visitor, ())) {
                                core::ops::ControlFlow::Continue(()) =>
                                    (),
                                    #[allow(unreachable_code)]
                                    core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_ast_ir::visit::VisitorResult::branch(crate::visit::Visitable::visit(__binding_1,
                                        __visitor, ())) {
                                core::ops::ControlFlow::Continue(()) =>
                                    (),
                                    #[allow(unreachable_code)]
                                    core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as rustc_ast_ir::visit::VisitorResult>::output()
            }
        }
        impl<__V> crate::mut_visit::MutWalkable<__V> for DelimSpan where
            __V: crate::mut_visit::MutVisitor {
            fn walk_mut(&mut self, __visitor: &mut __V) {
                match *self {
                    DelimSpan {
                        open: ref mut __binding_0, close: ref mut __binding_1 } => {
                        {
                            crate::mut_visit::MutVisitable::visit_mut(__binding_0,
                                __visitor, ())
                        }
                        {
                            crate::mut_visit::MutVisitable::visit_mut(__binding_1,
                                __visitor, ())
                        }
                    }
                }
            }
        }
    };Walkable)]
1055pub struct DelimSpan {
1056    pub open: Span,
1057    pub close: Span,
1058}
1059
1060impl DelimSpan {
1061    pub fn from_single(sp: Span) -> Self {
1062        DelimSpan { open: sp, close: sp }
1063    }
1064
1065    pub fn from_pair(open: Span, close: Span) -> Self {
1066        DelimSpan { open, close }
1067    }
1068
1069    pub fn dummy() -> Self {
1070        Self::from_single(DUMMY_SP)
1071    }
1072
1073    pub fn entire(self) -> Span {
1074        self.open.with_hi(self.close.hi())
1075    }
1076}
1077
1078#[derive(#[automatically_derived]impl ::core::marker::Copy for DelimSpacing { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DelimSpacing {
}
#[automatically_derived]impl ::core::clone::Clone for DelimSpacing {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Spacing>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for DelimSpacing {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "DelimSpacing open close", &self.open, &&self.close)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    DelimSpacing {
}
#[automatically_derived]impl ::core::cmp::PartialEq for DelimSpacing {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.open == other.open && self.close == other.close
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for DelimSpacing {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Spacing>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for DelimSpacing {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.open, state);
        ::core::hash::Hash::hash(&self.close, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DelimSpacing {
            fn encode(&self, __encoder: &mut __E) {
                let DelimSpacing {
                        open: ref __binding_0, close: ref __binding_1 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for DelimSpacing {
            fn decode(__decoder: &mut __D) -> Self {
                DelimSpacing {
                    open: ::rustc_serialize::Decodable::decode(__decoder),
                    close: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for DelimSpacing
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    DelimSpacing { open: ref __binding_0, close: ref __binding_1
                        } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
1079pub struct DelimSpacing {
1080    pub open: Spacing,
1081    pub close: Spacing,
1082}
1083
1084impl DelimSpacing {
1085    pub fn new(open: Spacing, close: Spacing) -> DelimSpacing {
1086        DelimSpacing { open, close }
1087    }
1088}
1089
1090// Some types are used a lot. Make sure they don't unintentionally get bigger.
1091#[cfg(target_pointer_width = "64")]
1092mod size_asserts {
1093    use rustc_data_structures::static_assert_size;
1094
1095    use super::*;
1096    // tidy-alphabetical-start
1097    const _: [(); 8] = [(); ::std::mem::size_of::<LazyTokenStream>()];static_assert_size!(LazyTokenStream, 8);
1098    const _: [(); 88] = [(); ::std::mem::size_of::<LazyTokenStreamInner>()];static_assert_size!(LazyTokenStreamInner, 88);
1099    const _: [(); 8] = [(); ::std::mem::size_of::<Option<LazyTokenStream>>()];static_assert_size!(Option<LazyTokenStream>, 8); // must be small, used in many AST nodes
1100    const _: [(); 8] = [(); ::std::mem::size_of::<TokenStream>()];static_assert_size!(TokenStream, 8);
1101    const _: [(); 32] = [(); ::std::mem::size_of::<TokenTree>()];static_assert_size!(TokenTree, 32);
1102    // tidy-alphabetical-end
1103}