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.
67use std::borrow::Cow;
8use std::hash::Hash;
9use std::ops::Range;
10use std::sync::{Arc, LazyLock};
11use std::{cmp, fmt, iter, mem};
1213use 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;
1920use crate::ast::AttrStyle;
21use crate::ast_traits::HasTokens;
22use crate::token::{self, Delimiter, Token, TokenKind};
23use crate::{AttrVec, Attribute};
2425#[cfg(test)]
26mod tests;
2728/// 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`.
33Token(Token, Spacing),
34/// A delimited sequence of token trees.
35Delimited(DelimSpan, DelimSpacing, Delimiter, TokenStream),
36}
3738// Ensure all fields of `TokenTree` are `DynSend` and `DynSync`.
39fn _dummy()
40where
41Token: sync::DynSend + sync::DynSync,
42Spacing: sync::DynSend + sync::DynSync,
43DelimSpan: sync::DynSend + sync::DynSync,
44Delimiter: sync::DynSend + sync::DynSync,
45TokenStream: sync::DynSend + sync::DynSync,
46{
47}
4849impl TokenTree {
50/// Checks if this `TokenTree` is equal to the other, regardless of span/spacing information.
51pub fn eq_unspanned(&self, other: &TokenTree) -> bool {
52match (self, other) {
53 (TokenTree::Token(token, _), TokenTree::Token(token2, _)) => token.kind == token2.kind,
54 (TokenTree::Delimited(.., delim, tts), TokenTree::Delimited(.., delim2, tts2)) => {
55delim == delim2 && tts.iter().eq_by(tts2.iter(), |a, b| a.eq_unspanned(b))
56 }
57_ => false,
58 }
59 }
6061/// Retrieves the `TokenTree`'s span.
62pub fn span(&self) -> Span {
63match self {
64 TokenTree::Token(token, _) => token.span,
65 TokenTree::Delimited(sp, ..) => sp.entire(),
66 }
67 }
6869/// Create a `TokenTree::Token` with alone spacing.
70pub fn token_alone(kind: TokenKind, span: Span) -> TokenTree {
71 TokenTree::Token(Token::new(kind, span), Spacing::Alone)
72 }
7374/// Create a `TokenTree::Token` with joint spacing.
75pub fn token_joint(kind: TokenKind, span: Span) -> TokenTree {
76 TokenTree::Token(Token::new(kind, span), Spacing::Joint)
77 }
7879/// Create a `TokenTree::Token` with joint-hidden spacing.
80pub fn token_joint_hidden(kind: TokenKind, span: Span) -> TokenTree {
81 TokenTree::Token(Token::new(kind, span), Spacing::JointHidden)
82 }
8384pub fn uninterpolate(&self) -> Cow<'_, TokenTree> {
85match 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}
9495#[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> {
97pub node: T,
98pub tokens: Option<LazyTokenStream>,
99}
100101impl<T> WithTokens<T> {
102pub fn new(node: T) -> WithTokens<T> {
103WithTokens { node, tokens: None }
104 }
105106pub fn map<U>(self, f: impl FnOnce(T) -> U) -> WithTokens<U> {
107WithTokens { node: f(self.node), tokens: self.tokens }
108 }
109}
110111/// 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>);
115116impl LazyTokenStream {
117pub fn new_direct(stream: TokenStream) -> LazyTokenStream {
118LazyTokenStream(Arc::new(LazyTokenStreamInner::Direct(stream)))
119 }
120121pub 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 {
128LazyTokenStream(Arc::new(LazyTokenStreamInner::Pending {
129start_token,
130cursor_snapshot,
131num_calls,
132break_last_token,
133node_replacements,
134 }))
135 }
136137pub fn to_token_stream(&self) -> TokenStream {
138self.0.to_configured_token_stream(&mut keep_all)
139 }
140141pub fn to_configured_token_stream(&self, configure: &mut ConfigureFn<'_>) -> TokenStream {
142self.0.to_configured_token_stream(configure)
143 }
144145pub fn append_token_trees_to(&self, res: &mut Vec<TokenTree>) {
146self.0.append_token_trees_to(&mut keep_all, res);
147 }
148}
149150impl fmt::Debugfor LazyTokenStream {
151fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152f.write_fmt(format_args!("LazyTokenStream({0:?})", self.to_token_stream()))write!(f, "LazyTokenStream({:?})", self.to_token_stream())153 }
154}
155156impl<S: SpanEncoder> Encodable<S> for LazyTokenStream {
157fn encode(&self, _s: &mut S) {
158{
::core::panicking::panic_fmt(format_args!("Attempted to encode LazyTokenStream"));
};panic!("Attempted to encode LazyTokenStream");
159 }
160}
161162impl<D: SpanDecoder> Decodable<D> for LazyTokenStream {
163fn decode(_d: &mut D) -> Self {
164{
::core::panicking::panic_fmt(format_args!("Attempted to decode LazyTokenStream"));
};panic!("Attempted to decode LazyTokenStream");
165 }
166}
167168impl StableHashfor LazyTokenStream {
169fn 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}
173174/// 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>);
177178/// 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>);
183184/// 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>);
203204/// See the comment on `ParserReplacement`.
205pub type NodeReplacement = (NodeRange, Option<AttrsTarget>);
206207impl 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)`.
217pub fn new(ParserRange(parser_range): ParserRange, start_pos: u32) -> NodeRange {
218if !!parser_range.is_empty() {
::core::panicking::panic("assertion failed: !parser_range.is_empty()")
};assert!(!parser_range.is_empty());
219if !(parser_range.start >= start_pos) {
::core::panicking::panic("assertion failed: parser_range.start >= start_pos")
};assert!(parser_range.start >= start_pos);
220NodeRange((parser_range.start - start_pos)..(parser_range.end - start_pos))
221 }
222}
223224enum LazyTokenStreamInner {
225// The token stream has already been produced.
226Direct(TokenStream),
227228// 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.
239Pending {
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}
247248/// 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;
251252/// A `ConfigureFn` that keeps the target, i.e. the node and its tokens.
253fn keep_all(_: &mut AttrsTarget) -> bool {
254true
255}
256257impl LazyTokenStreamInner {
258fn to_configured_token_stream(&self, configure: &mut ConfigureFn<'_>) -> TokenStream {
259match self {
260 LazyTokenStreamInner::Direct(stream) => stream.clone(),
261 LazyTokenStreamInner::Pending { .. } => {
262let mut res = ::alloc::vec::Vec::new()vec![];
263self.append_token_trees_to(configure, &mut res);
264TokenStream::new(res)
265 }
266 }
267 }
268269fn append_token_trees_to(&self, configure: &mut ConfigureFn<'_>, res: &mut Vec<TokenTree>) {
270match 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.
284let mut cursor_snapshot = cursor_snapshot.clone();
285let tokens = iter::once(FlatToken::Token(*start_token))
286 .chain(iter::repeat_with(|| FlatToken::Token(cursor_snapshot.next_and_bump())))
287 .take(*num_callsas usize);
288if node_replacements.is_empty() {
289append_flat_tokens_as_token_trees_to(tokens, *break_last_token, configure, res);
290 } else {
291let mut tokens: Vec<_> = tokens.collect();
292let mut node_replacements = node_replacements.to_vec();
293node_replacements.sort_by_key(|(range, _)| range.0.start);
294295#[cfg(debug_assertions)]
296for [(node_range, tokens), (next_node_range, next_tokens)] in
297node_replacements.array_windows()
298 {
299if !(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 }
309310// 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.
323for (node_range, target) in node_replacements.into_iter().rev() {
324if !!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);
329330// 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.
334let 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 }
343append_flat_tokens_as_token_trees_to(
344tokens.into_iter(),
345*break_last_token,
346configure,
347res,
348 );
349 }
350 }
351 }
352 }
353}
354355/// 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.
363Token((Token, Spacing)),
364/// Holds the `AttrsTarget` for an AST node. The `AttrsTarget` is expanded directly into the
365 /// constructed `TokenStream`.
366AttrsTarget(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.
369Empty,
370}
371372/// 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)]
383struct FrameData {
384// This is `None` for the first frame, `Some` for all others.
385open_delim_sp: Option<(Delimiter, Span, Spacing)>,
386 inner: Vec<TokenTree>,
387 }
388389// The stack always has at least one element. Storing it separately makes for shorter code.
390let mut stack_top = FrameData { open_delim_sp: None, inner: mem::take(res) };
391let mut stack_rest = ::alloc::vec::Vec::new()vec![];
392for flat_token in iter {
393match flat_token {
394 FlatToken::Token((token @ Token { kind, span }, spacing)) => {
395if 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.
404let Some(frame) = stack_rest.pop() else {
405*res = stack_top.inner;
406return;
407 };
408let frame_data = mem::replace(&mut stack_top, frame);
409let (open_delim, open_sp, open_spacing) = frame_data.open_delim_sp.unwrap();
410if !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);
414let dspan = DelimSpan::from_pair(open_sp, span);
415let dspacing = DelimSpacing::new(open_spacing, spacing);
416let stream = TokenStream::new(frame_data.inner);
417let 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) => {
424if 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 }
436437if break_last_token > 0 {
438let last_token = stack_top.inner.pop().unwrap();
439if let TokenTree::Token(last_token, spacing) = last_token {
440let (unglued, _) = last_token.kind.break_two_token_op(break_last_token).unwrap();
441442// Tokens are always ASCII chars, so we can use byte arithmetic here.
443let mut first_span = last_token.span.shrink_to_lo();
444first_span =
445first_span.with_hi(first_span.lo() + rustc_span::BytePos(break_last_token));
446447stack_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 }
452453*res = stack_top.inner;
454}
455456// 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) {
470let idx = attrs.partition_point(|attr| #[allow(non_exhaustive_omitted_patterns)] match attr.style {
crate::AttrStyle::Outer => true,
_ => false,
}matches!(attr.style, crate::AttrStyle::Outer));
471let (outer_attrs, inner_attrs) = attrs.split_at(idx);
472473// Add outer attribute tokens.
474for attr in outer_attrs {
475 attr.append_token_trees_to(res);
476 }
477478// Add target AST node tokens.
479target_tokens.0.append_token_trees_to(configure, res);
480481// Insert inner attribute tokens.
482if !inner_attrs.is_empty() {
483let found = insert_inner_attrs(inner_attrs, res);
484if !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 }
486487// 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.
500fn insert_inner_attrs(inner_attrs: &[Attribute], tts: &mut Vec<TokenTree>) -> bool {
501for tree in tts.iter_mut().rev() {
502if let TokenTree::Delimited(span, spacing, Delimiter::Brace, stream) = tree {
503// Found it: the rightmost, outermost braced group.
504let mut tts = ::alloc::vec::Vec::new()vec![];
505for inner_attr in inner_attrs {
506 inner_attr.append_token_trees_to(&mut tts);
507 }
508 tts.extend(stream.0.iter().cloned());
509let stream = TokenStream::new(tts);
510*tree = TokenTree::Delimited(*span, *spacing, Delimiter::Brace, stream);
511return true;
512 } else if let TokenTree::Delimited(span, spacing, Delimiter::Invisible(src), stream) =
513 tree
514 {
515// Recurse inside invisible delimiters.
516let mut vec: Vec<_> = stream.iter().cloned().collect();
517if insert_inner_attrs(inner_attrs, &mut vec) {
518*tree = TokenTree::Delimited(
519*span,
520*spacing,
521 Delimiter::Invisible(*src),
522 TokenStream::new(vec),
523 );
524return true;
525 }
526 }
527 }
528false
529}
530}
531532/// 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.
548pub attrs: AttrVec,
549/// The underlying tokens for the attribute target that `attrs`
550 /// are applied to
551pub tokens: LazyTokenStream,
552}
553554/// 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.
575Alone,
576577/// 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.
589Joint,
590591/// 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).
611JointHidden,
612}
613614/// A shared empty token stream, used to avoid an unnecessary `Arc` allocation for every empty
615/// token stream.
616static EMPTY_TOKEN_STREAM: LazyLock<TokenStream> =
617LazyLock::new(|| TokenStream(Arc::new(Vec::new())));
618619/// 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>>);
622623impl TokenStream {
624pub fn new(tts: Vec<TokenTree>) -> TokenStream {
625if tts.is_empty() { TokenStream::default() } else { TokenStream(Arc::new(tts)) }
626 }
627628pub fn is_empty(&self) -> bool {
629self.0.is_empty()
630 }
631632pub fn len(&self) -> usize {
633self.0.len()
634 }
635636pub fn get(&self, index: usize) -> Option<&TokenTree> {
637self.0.get(index)
638 }
639640pub fn iter(&self) -> TokenStreamIter<'_> {
641TokenStreamIter::new(self)
642 }
643644/// 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`.
648pub fn token_alone(kind: TokenKind, span: Span) -> TokenStream {
649TokenStream::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 }
651652pub fn from_ast(node: &(impl HasTokens + fmt::Debug)) -> TokenStream {
653let tokens = node.tokens().unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("missing tokens for node: {0:?}",
node));
}panic!("missing tokens for node: {:?}", node));
654let mut tts = ::alloc::vec::Vec::new()vec![];
655append_attrs_and_stream_as_token_trees_to(node.attrs(), tokens, &mut keep_all, &mut tts);
656TokenStream::new(tts)
657 }
658659// If `vec` is not empty, try to glue `tt` onto its last token. The return
660 // value indicates if gluing took place.
661fn try_glue_to_last(vec: &mut [TokenTree], tt: &TokenTree) -> bool {
662if let Some(TokenTree::Token(last_tok, Spacing::Joint | Spacing::JointHidden)) = vec.last()
663 && let TokenTree::Token(tok, spacing) = tt664 && 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);
668true
669} else {
670false
671}
672 }
673674/// 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`.
680pub fn push_tree_with_gluing(&mut self, tt: TokenTree) {
681let vec_mut = Arc::make_mut(&mut self.0);
682683if Self::try_glue_to_last(vec_mut, &tt) {
684// nothing else to do
685} else {
686vec_mut.push(tt);
687 }
688 }
689690/// 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`.
697pub fn push_stream_with_gluing(&mut self, stream: TokenStream) {
698let vec_mut = Arc::make_mut(&mut self.0);
699700let stream_iter = stream.0.iter().cloned();
701702if 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`.
706vec_mut.extend(stream_iter.skip(1));
707 } else {
708// Append all of `stream`.
709vec_mut.extend(stream_iter);
710 }
711 }
712713/// 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.
716pub fn desugar_doc_comments(&mut self) {
717if let Some(desugared_stream) = desugar_inner(self.clone()) {
718*self = desugared_stream;
719 }
720721// The return value is `None` if nothing in `stream` changed.
722fn desugar_inner(mut stream: TokenStream) -> Option<TokenStream> {
723let mut i = 0;
724let mut modified = false;
725while let Some(tt) = stream.0.get(i) {
726match tt {
727&TokenTree::Token(
728 Token { kind: token::DocComment(_, attr_style, data), span },
729 _spacing,
730 ) => {
731let desugared = desugared_tts(attr_style, data, span);
732let desugared_len = desugared.len();
733 Arc::make_mut(&mut stream.0).splice(i..i + 1, desugared);
734 modified = true;
735 i += desugared_len;
736 }
737738&TokenTree::Token(..) => i += 1,
739740&TokenTree::Delimited(sp, spacing, delim, ref delim_stream) => {
741if let Some(desugared_delim_stream) = desugar_inner(delim_stream.clone()) {
742let 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 }
751if modified { Some(stream) } else { None }
752 }
753754fn 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)
760let mut num_of_hashes = 0;
761let mut count = 0;
762for 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 }
770771// `/// foo` becomes `[doc = r"foo"]`.
772let delim_span = DelimSpan::from_single(span);
773let body = TokenTree::Delimited(
774delim_span,
775DelimSpacing::new(Spacing::JointHidden, Spacing::Alone),
776 Delimiter::Bracket,
777 [
778TokenTree::token_alone(token::Ident(sym::doc, token::IdentKind::Normal), span),
779TokenTree::token_alone(token::Eq, span),
780TokenTree::token_alone(
781TokenKind::lit(token::StrRaw(num_of_hashes), data, None),
782span,
783 ),
784 ]
785 .into_iter()
786 .collect::<TokenStream>(),
787 );
788789if 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 }
800801/// 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.
803pub fn add_comma(&self) -> Option<(TokenStream, Span)> {
804// Used to suggest if a user writes `foo!(a b);`
805let mut suggestion = None;
806let mut iter = self.0.iter().enumerate().peekable();
807while let Some((pos, ts)) = iter.next() {
808if let Some((_, next)) = iter.peek() {
809let 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 };
822let sp = sp.shrink_to_hi();
823let comma = TokenTree::token_alone(token::Comma, sp);
824 suggestion = Some((pos, comma, sp));
825 }
826 }
827if let Some((pos, comma, sp)) = suggestion {
828let mut new_stream = Vec::with_capacity(self.0.len() + 1);
829let parts = self.0.split_at(pos + 1);
830new_stream.extend_from_slice(parts.0);
831new_stream.push(comma);
832new_stream.extend_from_slice(parts.1);
833return Some((TokenStream::new(new_stream), sp));
834 }
835None836 }
837}
838839impl Defaultfor TokenStream {
840fn default() -> TokenStream {
841EMPTY_TOKEN_STREAM.clone()
842 }
843}
844845impl FromIterator<TokenTree> for TokenStream {
846fn from_iter<I: IntoIterator<Item = TokenTree>>(iter: I) -> Self {
847TokenStream::new(iter.into_iter().collect::<Vec<TokenTree>>())
848 }
849}
850851impl StableHashfor TokenStream {
852fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
853self.0.as_slice().stable_hash(hcx, hasher);
854 }
855}
856857#[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>);
859860impl<'t> TokenStreamIter<'t> {
861fn new(stream: &'t TokenStream) -> Self {
862TokenStreamIter(stream.0.as_slice().iter())
863 }
864865// 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.
868pub fn peek(&self) -> Option<&'t TokenTree> {
869self.0.as_slice().first()
870 }
871}
872873impl<'t> Iteratorfor TokenStreamIter<'t> {
874type Item = &'t TokenTree;
875876fn next(&mut self) -> Option<&'t TokenTree> {
877self.0.next()
878 }
879880fn size_hint(&self) -> (usize, Option<usize>) {
881self.0.size_hint()
882 }
883}
884885#[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).
889next_idx: usize,
890}
891892impl TokenTreeCursor {
893#[inline]
894fn new(stream: TokenStream) -> Self {
895TokenTreeCursor { stream, next_idx: 0 }
896 }
897898/// 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]
901fn curr(&self) -> Option<&TokenTree> {
902if true {
if !(self.next_idx > 0) {
::core::panicking::panic("assertion failed: self.next_idx > 0")
};
};debug_assert!(self.next_idx > 0);
903self.stream.get(self.next_idx - 1)
904 }
905906/// Gets the next token tree without advancing.
907#[inline]
908fn next(&self) -> Option<&TokenTree> {
909self.stream.get(self.next_idx)
910 }
911912/// 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]
915fn 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);
917self.stream.get(self.next_idx + (n - 1))
918 }
919920/// Move the cursor to the next token tree.
921#[inline]
922fn bump(&mut self) {
923self.next_idx += 1;
924 }
925926/// For skipping ahead in rare circumstances.
927#[inline]
928fn bump_to_end(&mut self) {
929self.next_idx = self.stream.len();
930 }
931}
932933/// 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.
944curr: TokenTreeCursor,
945946// 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`.
949stack: Vec<TokenTreeCursor>,
950}
951952impl TokenCursor {
953#[inline]
954pub fn new(stream: TokenStream) -> Self {
955TokenCursor { curr: TokenTreeCursor::new(stream), stack: ::alloc::vec::Vec::new()vec![] }
956 }
957958/// Gets the next token and advances the cursor by one.
959pub fn next_and_bump(&mut self) -> (Token, Spacing) {
960self.inlined_next_and_bump()
961 }
962963/// 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]
966pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> {
967self.curr.look_ahead(n)
968 }
969970/// 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]
973pub fn look_ahead_past_close_delim(&self) -> Option<&TokenTree> {
974self.stack.last().unwrap().next()
975 }
976977/// Clones the `TokenTree::Delimited` that we are currently within. Panics if we are not within
978 /// a delimited sequence.
979#[inline]
980pub fn clone_enclosing_delim(&self) -> TokenTree {
981self.stack.last().unwrap().curr().unwrap().clone()
982 }
983984/// For skipping to the end of the current sequence, in rare circumstances.
985#[inline]
986pub fn bump_to_end(&mut self) {
987self.curr.bump_to_end()
988 }
989990/// Note: the outermost stream has depth of 0.
991#[inline]
992pub fn depth(&self) -> usize {
993self.stack.len()
994 }
995996/// Returns details about the parent delimited sequence, if there is one.
997#[inline]
998pub fn parent_delim_and_span(&self) -> Option<(Delimiter, DelimSpan)> {
999if let Some(last) = self.stack.last()
1000 && let Some(TokenTree::Delimited(span, _, delim, _)) = last.curr()
1001 {
1002Some((*delim, *span))
1003 } else {
1004None1005 }
1006 }
10071008/// This always-inlined version should only be used on hot code paths.
1009#[inline(always)]
1010pub fn inlined_next_and_bump(&mut self) -> (Token, Spacing) {
1011loop {
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.
1015if let Some(tree) = self.curr.next() {
1016match tree {
1017&TokenTree::Token(token, spacing) => {
1018if true {
if !!token.kind.is_delim() {
::core::panicking::panic("assertion failed: !token.kind.is_delim()")
};
};debug_assert!(!token.kind.is_delim());
1019let res = (token, spacing);
1020self.curr.bump();
1021return res;
1022 }
1023&TokenTree::Delimited(sp, spacing, delim, ref tts) => {
1024let trees = TokenTreeCursor::new(tts.clone());
1025self.curr.bump(); // move past the `Delimited`
1026self.stack.push(mem::replace(&mut self.curr, trees));
1027if !delim.skip() {
1028return (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.
1035let 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 };
1038self.curr = parent;
1039if !delim.skip() {
1040return (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.
1047return (Token::new(token::Eof, DUMMY_SP), Spacing::Alone);
1048 }
1049 }
1050 }
1051}
10521053#[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 {
1056pub open: Span,
1057pub close: Span,
1058}
10591060impl DelimSpan {
1061pub fn from_single(sp: Span) -> Self {
1062DelimSpan { open: sp, close: sp }
1063 }
10641065pub fn from_pair(open: Span, close: Span) -> Self {
1066DelimSpan { open, close }
1067 }
10681069pub fn dummy() -> Self {
1070Self::from_single(DUMMY_SP)
1071 }
10721073pub fn entire(self) -> Span {
1074self.open.with_hi(self.close.hi())
1075 }
1076}
10771078#[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 {
1080pub open: Spacing,
1081pub close: Spacing,
1082}
10831084impl DelimSpacing {
1085pub fn new(open: Spacing, close: Spacing) -> DelimSpacing {
1086DelimSpacing { open, close }
1087 }
1088}
10891090// Some types are used a lot. Make sure they don't unintentionally get bigger.
1091#[cfg(target_pointer_width = "64")]
1092mod size_asserts {
1093use rustc_data_structures::static_assert_size;
10941095use super::*;
1096// tidy-alphabetical-start
1097const _: [(); 8] = [(); ::std::mem::size_of::<LazyTokenStream>()];static_assert_size!(LazyTokenStream, 8);
1098const _: [(); 88] = [(); ::std::mem::size_of::<LazyTokenStreamInner>()];static_assert_size!(LazyTokenStreamInner, 88);
1099const _: [(); 8] = [(); ::std::mem::size_of::<Option<LazyTokenStream>>()];static_assert_size!(Option<LazyTokenStream>, 8); // must be small, used in many AST nodes
1100const _: [(); 8] = [(); ::std::mem::size_of::<TokenStream>()];static_assert_size!(TokenStream, 8);
1101const _: [(); 32] = [(); ::std::mem::size_of::<TokenTree>()];static_assert_size!(TokenTree, 32);
1102// tidy-alphabetical-end
1103}