proc_macro2/
lib.rs

1//! [![github]](https://github.com/dtolnay/proc-macro2) [![crates-io]](https://crates.io/crates/proc-macro2) [![docs-rs]](crate)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6//!
7//! <br>
8//!
9//! A wrapper around the procedural macro API of the compiler's [`proc_macro`]
10//! crate. This library serves two purposes:
11//!
12//! [`proc_macro`]: https://doc.rust-lang.org/proc_macro/
13//!
14//! - **Bring proc-macro-like functionality to other contexts like build.rs and
15//!   main.rs.** Types from `proc_macro` are entirely specific to procedural
16//!   macros and cannot ever exist in code outside of a procedural macro.
17//!   Meanwhile `proc_macro2` types may exist anywhere including non-macro code.
18//!   By developing foundational libraries like [syn] and [quote] against
19//!   `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem
20//!   becomes easily applicable to many other use cases and we avoid
21//!   reimplementing non-macro equivalents of those libraries.
22//!
23//! - **Make procedural macros unit testable.** As a consequence of being
24//!   specific to procedural macros, nothing that uses `proc_macro` can be
25//!   executed from a unit test. In order for helper libraries or components of
26//!   a macro to be testable in isolation, they must be implemented using
27//!   `proc_macro2`.
28//!
29//! [syn]: https://github.com/dtolnay/syn
30//! [quote]: https://github.com/dtolnay/quote
31//!
32//! # Usage
33//!
34//! The skeleton of a typical procedural macro typically looks like this:
35//!
36//! ```
37//! extern crate proc_macro;
38//!
39//! # const IGNORE: &str = stringify! {
40//! #[proc_macro_derive(MyDerive)]
41//! # };
42//! # #[cfg(wrap_proc_macro)]
43//! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
44//!     let input = proc_macro2::TokenStream::from(input);
45//!
46//!     let output: proc_macro2::TokenStream = {
47//!         /* transform input */
48//!         # input
49//!     };
50//!
51//!     proc_macro::TokenStream::from(output)
52//! }
53//! ```
54//!
55//! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to
56//! propagate parse errors correctly back to the compiler when parsing fails.
57//!
58//! [`parse_macro_input!`]: https://docs.rs/syn/2.0/syn/macro.parse_macro_input.html
59//!
60//! # Unstable features
61//!
62//! The default feature set of proc-macro2 tracks the most recent stable
63//! compiler API. Functionality in `proc_macro` that is not yet stable is not
64//! exposed by proc-macro2 by default.
65//!
66//! To opt into the additional APIs available in the most recent nightly
67//! compiler, the `procmacro2_semver_exempt` config flag must be passed to
68//! rustc. We will polyfill those nightly-only APIs back to Rust 1.56.0. As
69//! these are unstable APIs that track the nightly compiler, minor versions of
70//! proc-macro2 may make breaking changes to them at any time.
71//!
72//! ```sh
73//! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build
74//! ```
75//!
76//! Note that this must not only be done for your crate, but for any crate that
77//! depends on your crate. This infectious nature is intentional, as it serves
78//! as a reminder that you are outside of the normal semver guarantees.
79//!
80//! Semver exempt methods are marked as such in the proc-macro2 documentation.
81//!
82//! # Thread-Safety
83//!
84//! Most types in this crate are `!Sync` because the underlying compiler
85//! types make use of thread-local memory, meaning they cannot be accessed from
86//! a different thread.
87
88// Proc-macro2 types in rustdoc of other crates get linked to here.
89#![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.89")]
90#![cfg_attr(any(proc_macro_span, super_unstable), feature(proc_macro_span))]
91#![cfg_attr(super_unstable, feature(proc_macro_def_site))]
92#![cfg_attr(docsrs, feature(doc_cfg))]
93#![deny(unsafe_op_in_unsafe_fn)]
94#![allow(
95    clippy::cast_lossless,
96    clippy::cast_possible_truncation,
97    clippy::checked_conversions,
98    clippy::doc_markdown,
99    clippy::incompatible_msrv,
100    clippy::items_after_statements,
101    clippy::iter_without_into_iter,
102    clippy::let_underscore_untyped,
103    clippy::manual_assert,
104    clippy::manual_range_contains,
105    clippy::missing_panics_doc,
106    clippy::missing_safety_doc,
107    clippy::must_use_candidate,
108    clippy::needless_doctest_main,
109    clippy::needless_lifetimes,
110    clippy::new_without_default,
111    clippy::return_self_not_must_use,
112    clippy::shadow_unrelated,
113    clippy::trivially_copy_pass_by_ref,
114    clippy::unnecessary_wraps,
115    clippy::unused_self,
116    clippy::used_underscore_binding,
117    clippy::vec_init_then_push
118)]
119
120#[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))]
121compile_error! {"\
122    Something is not right. If you've tried to turn on \
123    procmacro2_semver_exempt, you need to ensure that it \
124    is turned on for the compilation of the proc-macro2 \
125    build script as well.
126"}
127
128#[cfg(all(
129    procmacro2_nightly_testing,
130    feature = "proc-macro",
131    not(proc_macro_span)
132))]
133compile_error! {"\
134    Build script probe failed to compile.
135"}
136
137extern crate alloc;
138
139#[cfg(feature = "proc-macro")]
140extern crate proc_macro;
141
142mod marker;
143mod parse;
144mod rcvec;
145
146#[cfg(wrap_proc_macro)]
147mod detection;
148
149// Public for proc_macro2::fallback::force() and unforce(), but those are quite
150// a niche use case so we omit it from rustdoc.
151#[doc(hidden)]
152pub mod fallback;
153
154pub mod extra;
155
156#[cfg(not(wrap_proc_macro))]
157use crate::fallback as imp;
158#[path = "wrapper.rs"]
159#[cfg(wrap_proc_macro)]
160mod imp;
161
162#[cfg(span_locations)]
163mod location;
164
165use crate::extra::DelimSpan;
166use crate::marker::{ProcMacroAutoTraits, MARKER};
167use core::cmp::Ordering;
168use core::fmt::{self, Debug, Display};
169use core::hash::{Hash, Hasher};
170#[cfg(span_locations)]
171use core::ops::Range;
172use core::ops::RangeBounds;
173use core::str::FromStr;
174use std::error::Error;
175use std::ffi::CStr;
176#[cfg(procmacro2_semver_exempt)]
177use std::path::PathBuf;
178
179#[cfg(span_locations)]
180#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
181pub use crate::location::LineColumn;
182
183/// An abstract stream of tokens, or more concretely a sequence of token trees.
184///
185/// This type provides interfaces for iterating over token trees and for
186/// collecting token trees into one stream.
187///
188/// Token stream is both the input and output of `#[proc_macro]`,
189/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
190#[derive(Clone)]
191pub struct TokenStream {
192    inner: imp::TokenStream,
193    _marker: ProcMacroAutoTraits,
194}
195
196/// Error returned from `TokenStream::from_str`.
197pub struct LexError {
198    inner: imp::LexError,
199    _marker: ProcMacroAutoTraits,
200}
201
202impl TokenStream {
203    fn _new(inner: imp::TokenStream) -> Self {
204        TokenStream {
205            inner,
206            _marker: MARKER,
207        }
208    }
209
210    fn _new_fallback(inner: fallback::TokenStream) -> Self {
211        TokenStream {
212            inner: inner.into(),
213            _marker: MARKER,
214        }
215    }
216
217    /// Returns an empty `TokenStream` containing no token trees.
218    pub fn new() -> Self {
219        TokenStream::_new(imp::TokenStream::new())
220    }
221
222    /// Checks if this `TokenStream` is empty.
223    pub fn is_empty(&self) -> bool {
224        self.inner.is_empty()
225    }
226}
227
228/// `TokenStream::default()` returns an empty stream,
229/// i.e. this is equivalent with `TokenStream::new()`.
230impl Default for TokenStream {
231    fn default() -> Self {
232        TokenStream::new()
233    }
234}
235
236/// Attempts to break the string into tokens and parse those tokens into a token
237/// stream.
238///
239/// May fail for a number of reasons, for example, if the string contains
240/// unbalanced delimiters or characters not existing in the language.
241///
242/// NOTE: Some errors may cause panics instead of returning `LexError`. We
243/// reserve the right to change these errors into `LexError`s later.
244impl FromStr for TokenStream {
245    type Err = LexError;
246
247    fn from_str(src: &str) -> Result<TokenStream, LexError> {
248        let e = src.parse().map_err(|e| LexError {
249            inner: e,
250            _marker: MARKER,
251        })?;
252        Ok(TokenStream::_new(e))
253    }
254}
255
256#[cfg(feature = "proc-macro")]
257#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
258impl From<proc_macro::TokenStream> for TokenStream {
259    fn from(inner: proc_macro::TokenStream) -> Self {
260        TokenStream::_new(inner.into())
261    }
262}
263
264#[cfg(feature = "proc-macro")]
265#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
266impl From<TokenStream> for proc_macro::TokenStream {
267    fn from(inner: TokenStream) -> Self {
268        inner.inner.into()
269    }
270}
271
272impl From<TokenTree> for TokenStream {
273    fn from(token: TokenTree) -> Self {
274        TokenStream::_new(imp::TokenStream::from(token))
275    }
276}
277
278impl Extend<TokenTree> for TokenStream {
279    fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
280        self.inner.extend(streams);
281    }
282}
283
284impl Extend<TokenStream> for TokenStream {
285    fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
286        self.inner
287            .extend(streams.into_iter().map(|stream| stream.inner));
288    }
289}
290
291/// Collects a number of token trees into a single stream.
292impl FromIterator<TokenTree> for TokenStream {
293    fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
294        TokenStream::_new(streams.into_iter().collect())
295    }
296}
297impl FromIterator<TokenStream> for TokenStream {
298    fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
299        TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
300    }
301}
302
303/// Prints the token stream as a string that is supposed to be losslessly
304/// convertible back into the same token stream (modulo spans), except for
305/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
306/// numeric literals.
307impl Display for TokenStream {
308    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
309        Display::fmt(&self.inner, f)
310    }
311}
312
313/// Prints token in a form convenient for debugging.
314impl Debug for TokenStream {
315    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
316        Debug::fmt(&self.inner, f)
317    }
318}
319
320impl LexError {
321    pub fn span(&self) -> Span {
322        Span::_new(self.inner.span())
323    }
324}
325
326impl Debug for LexError {
327    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
328        Debug::fmt(&self.inner, f)
329    }
330}
331
332impl Display for LexError {
333    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
334        Display::fmt(&self.inner, f)
335    }
336}
337
338impl Error for LexError {}
339
340/// The source file of a given `Span`.
341///
342/// This type is semver exempt and not exposed by default.
343#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
344#[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
345#[derive(Clone, PartialEq, Eq)]
346pub struct SourceFile {
347    inner: imp::SourceFile,
348    _marker: ProcMacroAutoTraits,
349}
350
351#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
352impl SourceFile {
353    fn _new(inner: imp::SourceFile) -> Self {
354        SourceFile {
355            inner,
356            _marker: MARKER,
357        }
358    }
359
360    /// Get the path to this source file.
361    ///
362    /// ### Note
363    ///
364    /// If the code span associated with this `SourceFile` was generated by an
365    /// external macro, this may not be an actual path on the filesystem. Use
366    /// [`is_real`] to check.
367    ///
368    /// Also note that even if `is_real` returns `true`, if
369    /// `--remap-path-prefix` was passed on the command line, the path as given
370    /// may not actually be valid.
371    ///
372    /// [`is_real`]: #method.is_real
373    pub fn path(&self) -> PathBuf {
374        self.inner.path()
375    }
376
377    /// Returns `true` if this source file is a real source file, and not
378    /// generated by an external macro's expansion.
379    pub fn is_real(&self) -> bool {
380        self.inner.is_real()
381    }
382}
383
384#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
385impl Debug for SourceFile {
386    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
387        Debug::fmt(&self.inner, f)
388    }
389}
390
391/// A region of source code, along with macro expansion information.
392#[derive(Copy, Clone)]
393pub struct Span {
394    inner: imp::Span,
395    _marker: ProcMacroAutoTraits,
396}
397
398impl Span {
399    fn _new(inner: imp::Span) -> Self {
400        Span {
401            inner,
402            _marker: MARKER,
403        }
404    }
405
406    fn _new_fallback(inner: fallback::Span) -> Self {
407        Span {
408            inner: inner.into(),
409            _marker: MARKER,
410        }
411    }
412
413    /// The span of the invocation of the current procedural macro.
414    ///
415    /// Identifiers created with this span will be resolved as if they were
416    /// written directly at the macro call location (call-site hygiene) and
417    /// other code at the macro call site will be able to refer to them as well.
418    pub fn call_site() -> Self {
419        Span::_new(imp::Span::call_site())
420    }
421
422    /// The span located at the invocation of the procedural macro, but with
423    /// local variables, labels, and `$crate` resolved at the definition site
424    /// of the macro. This is the same hygiene behavior as `macro_rules`.
425    pub fn mixed_site() -> Self {
426        Span::_new(imp::Span::mixed_site())
427    }
428
429    /// A span that resolves at the macro definition site.
430    ///
431    /// This method is semver exempt and not exposed by default.
432    #[cfg(procmacro2_semver_exempt)]
433    #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
434    pub fn def_site() -> Self {
435        Span::_new(imp::Span::def_site())
436    }
437
438    /// Creates a new span with the same line/column information as `self` but
439    /// that resolves symbols as though it were at `other`.
440    pub fn resolved_at(&self, other: Span) -> Span {
441        Span::_new(self.inner.resolved_at(other.inner))
442    }
443
444    /// Creates a new span with the same name resolution behavior as `self` but
445    /// with the line/column information of `other`.
446    pub fn located_at(&self, other: Span) -> Span {
447        Span::_new(self.inner.located_at(other.inner))
448    }
449
450    /// Convert `proc_macro2::Span` to `proc_macro::Span`.
451    ///
452    /// This method is available when building with a nightly compiler, or when
453    /// building with rustc 1.29+ *without* semver exempt features.
454    ///
455    /// # Panics
456    ///
457    /// Panics if called from outside of a procedural macro. Unlike
458    /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
459    /// the context of a procedural macro invocation.
460    #[cfg(wrap_proc_macro)]
461    pub fn unwrap(self) -> proc_macro::Span {
462        self.inner.unwrap()
463    }
464
465    // Soft deprecated. Please use Span::unwrap.
466    #[cfg(wrap_proc_macro)]
467    #[doc(hidden)]
468    pub fn unstable(self) -> proc_macro::Span {
469        self.unwrap()
470    }
471
472    /// The original source file into which this span points.
473    ///
474    /// This method is semver exempt and not exposed by default.
475    #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
476    #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
477    pub fn source_file(&self) -> SourceFile {
478        SourceFile::_new(self.inner.source_file())
479    }
480
481    /// Returns the span's byte position range in the source file.
482    ///
483    /// This method requires the `"span-locations"` feature to be enabled.
484    ///
485    /// When executing in a procedural macro context, the returned range is only
486    /// accurate if compiled with a nightly toolchain. The stable toolchain does
487    /// not have this information available. When executing outside of a
488    /// procedural macro, such as main.rs or build.rs, the byte range is always
489    /// accurate regardless of toolchain.
490    #[cfg(span_locations)]
491    #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
492    pub fn byte_range(&self) -> Range<usize> {
493        self.inner.byte_range()
494    }
495
496    /// Get the starting line/column in the source file for this span.
497    ///
498    /// This method requires the `"span-locations"` feature to be enabled.
499    ///
500    /// When executing in a procedural macro context, the returned line/column
501    /// are only meaningful if compiled with a nightly toolchain. The stable
502    /// toolchain does not have this information available. When executing
503    /// outside of a procedural macro, such as main.rs or build.rs, the
504    /// line/column are always meaningful regardless of toolchain.
505    #[cfg(span_locations)]
506    #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
507    pub fn start(&self) -> LineColumn {
508        self.inner.start()
509    }
510
511    /// Get the ending line/column in the source file for this span.
512    ///
513    /// This method requires the `"span-locations"` feature to be enabled.
514    ///
515    /// When executing in a procedural macro context, the returned line/column
516    /// are only meaningful if compiled with a nightly toolchain. The stable
517    /// toolchain does not have this information available. When executing
518    /// outside of a procedural macro, such as main.rs or build.rs, the
519    /// line/column are always meaningful regardless of toolchain.
520    #[cfg(span_locations)]
521    #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
522    pub fn end(&self) -> LineColumn {
523        self.inner.end()
524    }
525
526    /// Create a new span encompassing `self` and `other`.
527    ///
528    /// Returns `None` if `self` and `other` are from different files.
529    ///
530    /// Warning: the underlying [`proc_macro::Span::join`] method is
531    /// nightly-only. When called from within a procedural macro not using a
532    /// nightly compiler, this method will always return `None`.
533    ///
534    /// [`proc_macro::Span::join`]: https://doc.rust-lang.org/proc_macro/struct.Span.html#method.join
535    pub fn join(&self, other: Span) -> Option<Span> {
536        self.inner.join(other.inner).map(Span::_new)
537    }
538
539    /// Compares two spans to see if they're equal.
540    ///
541    /// This method is semver exempt and not exposed by default.
542    #[cfg(procmacro2_semver_exempt)]
543    #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
544    pub fn eq(&self, other: &Span) -> bool {
545        self.inner.eq(&other.inner)
546    }
547
548    /// Returns the source text behind a span. This preserves the original
549    /// source code, including spaces and comments. It only returns a result if
550    /// the span corresponds to real source code.
551    ///
552    /// Note: The observable result of a macro should only rely on the tokens
553    /// and not on this source text. The result of this function is a best
554    /// effort to be used for diagnostics only.
555    pub fn source_text(&self) -> Option<String> {
556        self.inner.source_text()
557    }
558}
559
560/// Prints a span in a form convenient for debugging.
561impl Debug for Span {
562    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
563        Debug::fmt(&self.inner, f)
564    }
565}
566
567/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
568#[derive(Clone)]
569pub enum TokenTree {
570    /// A token stream surrounded by bracket delimiters.
571    Group(Group),
572    /// An identifier.
573    Ident(Ident),
574    /// A single punctuation character (`+`, `,`, `$`, etc.).
575    Punct(Punct),
576    /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
577    Literal(Literal),
578}
579
580impl TokenTree {
581    /// Returns the span of this tree, delegating to the `span` method of
582    /// the contained token or a delimited stream.
583    pub fn span(&self) -> Span {
584        match self {
585            TokenTree::Group(t) => t.span(),
586            TokenTree::Ident(t) => t.span(),
587            TokenTree::Punct(t) => t.span(),
588            TokenTree::Literal(t) => t.span(),
589        }
590    }
591
592    /// Configures the span for *only this token*.
593    ///
594    /// Note that if this token is a `Group` then this method will not configure
595    /// the span of each of the internal tokens, this will simply delegate to
596    /// the `set_span` method of each variant.
597    pub fn set_span(&mut self, span: Span) {
598        match self {
599            TokenTree::Group(t) => t.set_span(span),
600            TokenTree::Ident(t) => t.set_span(span),
601            TokenTree::Punct(t) => t.set_span(span),
602            TokenTree::Literal(t) => t.set_span(span),
603        }
604    }
605}
606
607impl From<Group> for TokenTree {
608    fn from(g: Group) -> Self {
609        TokenTree::Group(g)
610    }
611}
612
613impl From<Ident> for TokenTree {
614    fn from(g: Ident) -> Self {
615        TokenTree::Ident(g)
616    }
617}
618
619impl From<Punct> for TokenTree {
620    fn from(g: Punct) -> Self {
621        TokenTree::Punct(g)
622    }
623}
624
625impl From<Literal> for TokenTree {
626    fn from(g: Literal) -> Self {
627        TokenTree::Literal(g)
628    }
629}
630
631/// Prints the token tree as a string that is supposed to be losslessly
632/// convertible back into the same token tree (modulo spans), except for
633/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
634/// numeric literals.
635impl Display for TokenTree {
636    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
637        match self {
638            TokenTree::Group(t) => Display::fmt(t, f),
639            TokenTree::Ident(t) => Display::fmt(t, f),
640            TokenTree::Punct(t) => Display::fmt(t, f),
641            TokenTree::Literal(t) => Display::fmt(t, f),
642        }
643    }
644}
645
646/// Prints token tree in a form convenient for debugging.
647impl Debug for TokenTree {
648    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
649        // Each of these has the name in the struct type in the derived debug,
650        // so don't bother with an extra layer of indirection
651        match self {
652            TokenTree::Group(t) => Debug::fmt(t, f),
653            TokenTree::Ident(t) => {
654                let mut debug = f.debug_struct("Ident");
655                debug.field("sym", &format_args!("{}", t));
656                imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
657                debug.finish()
658            }
659            TokenTree::Punct(t) => Debug::fmt(t, f),
660            TokenTree::Literal(t) => Debug::fmt(t, f),
661        }
662    }
663}
664
665/// A delimited token stream.
666///
667/// A `Group` internally contains a `TokenStream` which is surrounded by
668/// `Delimiter`s.
669#[derive(Clone)]
670pub struct Group {
671    inner: imp::Group,
672}
673
674/// Describes how a sequence of token trees is delimited.
675#[derive(Copy, Clone, Debug, Eq, PartialEq)]
676pub enum Delimiter {
677    /// `( ... )`
678    Parenthesis,
679    /// `{ ... }`
680    Brace,
681    /// `[ ... ]`
682    Bracket,
683    /// `∅ ... ∅`
684    ///
685    /// An invisible delimiter, that may, for example, appear around tokens
686    /// coming from a "macro variable" `$var`. It is important to preserve
687    /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
688    /// Invisible delimiters may not survive roundtrip of a token stream through
689    /// a string.
690    ///
691    /// <div class="warning">
692    ///
693    /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
694    /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
695    /// of a proc_macro macro are preserved, and only in very specific circumstances.
696    /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
697    /// operator priorities as indicated above. The other `Delimiter` variants should be used
698    /// instead in this context. This is a rustc bug. For details, see
699    /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
700    ///
701    /// </div>
702    None,
703}
704
705impl Group {
706    fn _new(inner: imp::Group) -> Self {
707        Group { inner }
708    }
709
710    fn _new_fallback(inner: fallback::Group) -> Self {
711        Group {
712            inner: inner.into(),
713        }
714    }
715
716    /// Creates a new `Group` with the given delimiter and token stream.
717    ///
718    /// This constructor will set the span for this group to
719    /// `Span::call_site()`. To change the span you can use the `set_span`
720    /// method below.
721    pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
722        Group {
723            inner: imp::Group::new(delimiter, stream.inner),
724        }
725    }
726
727    /// Returns the punctuation used as the delimiter for this group: a set of
728    /// parentheses, square brackets, or curly braces.
729    pub fn delimiter(&self) -> Delimiter {
730        self.inner.delimiter()
731    }
732
733    /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
734    ///
735    /// Note that the returned token stream does not include the delimiter
736    /// returned above.
737    pub fn stream(&self) -> TokenStream {
738        TokenStream::_new(self.inner.stream())
739    }
740
741    /// Returns the span for the delimiters of this token stream, spanning the
742    /// entire `Group`.
743    ///
744    /// ```text
745    /// pub fn span(&self) -> Span {
746    ///            ^^^^^^^
747    /// ```
748    pub fn span(&self) -> Span {
749        Span::_new(self.inner.span())
750    }
751
752    /// Returns the span pointing to the opening delimiter of this group.
753    ///
754    /// ```text
755    /// pub fn span_open(&self) -> Span {
756    ///                 ^
757    /// ```
758    pub fn span_open(&self) -> Span {
759        Span::_new(self.inner.span_open())
760    }
761
762    /// Returns the span pointing to the closing delimiter of this group.
763    ///
764    /// ```text
765    /// pub fn span_close(&self) -> Span {
766    ///                        ^
767    /// ```
768    pub fn span_close(&self) -> Span {
769        Span::_new(self.inner.span_close())
770    }
771
772    /// Returns an object that holds this group's `span_open()` and
773    /// `span_close()` together (in a more compact representation than holding
774    /// those 2 spans individually).
775    pub fn delim_span(&self) -> DelimSpan {
776        DelimSpan::new(&self.inner)
777    }
778
779    /// Configures the span for this `Group`'s delimiters, but not its internal
780    /// tokens.
781    ///
782    /// This method will **not** set the span of all the internal tokens spanned
783    /// by this group, but rather it will only set the span of the delimiter
784    /// tokens at the level of the `Group`.
785    pub fn set_span(&mut self, span: Span) {
786        self.inner.set_span(span.inner);
787    }
788}
789
790/// Prints the group as a string that should be losslessly convertible back
791/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
792/// with `Delimiter::None` delimiters.
793impl Display for Group {
794    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
795        Display::fmt(&self.inner, formatter)
796    }
797}
798
799impl Debug for Group {
800    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
801        Debug::fmt(&self.inner, formatter)
802    }
803}
804
805/// A `Punct` is a single punctuation character like `+`, `-` or `#`.
806///
807/// Multicharacter operators like `+=` are represented as two instances of
808/// `Punct` with different forms of `Spacing` returned.
809#[derive(Clone)]
810pub struct Punct {
811    ch: char,
812    spacing: Spacing,
813    span: Span,
814}
815
816/// Whether a `Punct` is followed immediately by another `Punct` or followed by
817/// another token or whitespace.
818#[derive(Copy, Clone, Debug, Eq, PartialEq)]
819pub enum Spacing {
820    /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
821    Alone,
822    /// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.
823    ///
824    /// Additionally, single quote `'` can join with identifiers to form
825    /// lifetimes `'ident`.
826    Joint,
827}
828
829impl Punct {
830    /// Creates a new `Punct` from the given character and spacing.
831    ///
832    /// The `ch` argument must be a valid punctuation character permitted by the
833    /// language, otherwise the function will panic.
834    ///
835    /// The returned `Punct` will have the default span of `Span::call_site()`
836    /// which can be further configured with the `set_span` method below.
837    pub fn new(ch: char, spacing: Spacing) -> Self {
838        if let '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';'
839        | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch
840        {
841            Punct {
842                ch,
843                spacing,
844                span: Span::call_site(),
845            }
846        } else {
847            panic!("unsupported proc macro punctuation character {:?}", ch);
848        }
849    }
850
851    /// Returns the value of this punctuation character as `char`.
852    pub fn as_char(&self) -> char {
853        self.ch
854    }
855
856    /// Returns the spacing of this punctuation character, indicating whether
857    /// it's immediately followed by another `Punct` in the token stream, so
858    /// they can potentially be combined into a multicharacter operator
859    /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
860    /// so the operator has certainly ended.
861    pub fn spacing(&self) -> Spacing {
862        self.spacing
863    }
864
865    /// Returns the span for this punctuation character.
866    pub fn span(&self) -> Span {
867        self.span
868    }
869
870    /// Configure the span for this punctuation character.
871    pub fn set_span(&mut self, span: Span) {
872        self.span = span;
873    }
874}
875
876/// Prints the punctuation character as a string that should be losslessly
877/// convertible back into the same character.
878impl Display for Punct {
879    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
880        Display::fmt(&self.ch, f)
881    }
882}
883
884impl Debug for Punct {
885    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
886        let mut debug = fmt.debug_struct("Punct");
887        debug.field("char", &self.ch);
888        debug.field("spacing", &self.spacing);
889        imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
890        debug.finish()
891    }
892}
893
894/// A word of Rust code, which may be a keyword or legal variable name.
895///
896/// An identifier consists of at least one Unicode code point, the first of
897/// which has the XID_Start property and the rest of which have the XID_Continue
898/// property.
899///
900/// - The empty string is not an identifier. Use `Option<Ident>`.
901/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
902///
903/// An identifier constructed with `Ident::new` is permitted to be a Rust
904/// keyword, though parsing one through its [`Parse`] implementation rejects
905/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
906/// behaviour of `Ident::new`.
907///
908/// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html
909///
910/// # Examples
911///
912/// A new ident can be created from a string using the `Ident::new` function.
913/// A span must be provided explicitly which governs the name resolution
914/// behavior of the resulting identifier.
915///
916/// ```
917/// use proc_macro2::{Ident, Span};
918///
919/// fn main() {
920///     let call_ident = Ident::new("calligraphy", Span::call_site());
921///
922///     println!("{}", call_ident);
923/// }
924/// ```
925///
926/// An ident can be interpolated into a token stream using the `quote!` macro.
927///
928/// ```
929/// use proc_macro2::{Ident, Span};
930/// use quote::quote;
931///
932/// fn main() {
933///     let ident = Ident::new("demo", Span::call_site());
934///
935///     // Create a variable binding whose name is this ident.
936///     let expanded = quote! { let #ident = 10; };
937///
938///     // Create a variable binding with a slightly different name.
939///     let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
940///     let expanded = quote! { let #temp_ident = 10; };
941/// }
942/// ```
943///
944/// A string representation of the ident is available through the `to_string()`
945/// method.
946///
947/// ```
948/// # use proc_macro2::{Ident, Span};
949/// #
950/// # let ident = Ident::new("another_identifier", Span::call_site());
951/// #
952/// // Examine the ident as a string.
953/// let ident_string = ident.to_string();
954/// if ident_string.len() > 60 {
955///     println!("Very long identifier: {}", ident_string)
956/// }
957/// ```
958#[derive(Clone)]
959pub struct Ident {
960    inner: imp::Ident,
961    _marker: ProcMacroAutoTraits,
962}
963
964impl Ident {
965    fn _new(inner: imp::Ident) -> Self {
966        Ident {
967            inner,
968            _marker: MARKER,
969        }
970    }
971
972    /// Creates a new `Ident` with the given `string` as well as the specified
973    /// `span`.
974    ///
975    /// The `string` argument must be a valid identifier permitted by the
976    /// language, otherwise the function will panic.
977    ///
978    /// Note that `span`, currently in rustc, configures the hygiene information
979    /// for this identifier.
980    ///
981    /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
982    /// hygiene meaning that identifiers created with this span will be resolved
983    /// as if they were written directly at the location of the macro call, and
984    /// other code at the macro call site will be able to refer to them as well.
985    ///
986    /// Later spans like `Span::def_site()` will allow to opt-in to
987    /// "definition-site" hygiene meaning that identifiers created with this
988    /// span will be resolved at the location of the macro definition and other
989    /// code at the macro call site will not be able to refer to them.
990    ///
991    /// Due to the current importance of hygiene this constructor, unlike other
992    /// tokens, requires a `Span` to be specified at construction.
993    ///
994    /// # Panics
995    ///
996    /// Panics if the input string is neither a keyword nor a legal variable
997    /// name. If you are not sure whether the string contains an identifier and
998    /// need to handle an error case, use
999    /// <a href="https://docs.rs/syn/2.0/syn/fn.parse_str.html"><code
1000    ///   style="padding-right:0;">syn::parse_str</code></a><code
1001    ///   style="padding-left:0;">::&lt;Ident&gt;</code>
1002    /// rather than `Ident::new`.
1003    #[track_caller]
1004    pub fn new(string: &str, span: Span) -> Self {
1005        Ident::_new(imp::Ident::new_checked(string, span.inner))
1006    }
1007
1008    /// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The
1009    /// `string` argument must be a valid identifier permitted by the language
1010    /// (including keywords, e.g. `fn`). Keywords which are usable in path
1011    /// segments (e.g. `self`, `super`) are not supported, and will cause a
1012    /// panic.
1013    #[track_caller]
1014    pub fn new_raw(string: &str, span: Span) -> Self {
1015        Ident::_new(imp::Ident::new_raw_checked(string, span.inner))
1016    }
1017
1018    /// Returns the span of this `Ident`.
1019    pub fn span(&self) -> Span {
1020        Span::_new(self.inner.span())
1021    }
1022
1023    /// Configures the span of this `Ident`, possibly changing its hygiene
1024    /// context.
1025    pub fn set_span(&mut self, span: Span) {
1026        self.inner.set_span(span.inner);
1027    }
1028}
1029
1030impl PartialEq for Ident {
1031    fn eq(&self, other: &Ident) -> bool {
1032        self.inner == other.inner
1033    }
1034}
1035
1036impl<T> PartialEq<T> for Ident
1037where
1038    T: ?Sized + AsRef<str>,
1039{
1040    fn eq(&self, other: &T) -> bool {
1041        self.inner == other
1042    }
1043}
1044
1045impl Eq for Ident {}
1046
1047impl PartialOrd for Ident {
1048    fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
1049        Some(self.cmp(other))
1050    }
1051}
1052
1053impl Ord for Ident {
1054    fn cmp(&self, other: &Ident) -> Ordering {
1055        self.to_string().cmp(&other.to_string())
1056    }
1057}
1058
1059impl Hash for Ident {
1060    fn hash<H: Hasher>(&self, hasher: &mut H) {
1061        self.to_string().hash(hasher);
1062    }
1063}
1064
1065/// Prints the identifier as a string that should be losslessly convertible back
1066/// into the same identifier.
1067impl Display for Ident {
1068    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1069        Display::fmt(&self.inner, f)
1070    }
1071}
1072
1073impl Debug for Ident {
1074    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1075        Debug::fmt(&self.inner, f)
1076    }
1077}
1078
1079/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
1080/// byte character (`b'a'`), an integer or floating point number with or without
1081/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1082///
1083/// Boolean literals like `true` and `false` do not belong here, they are
1084/// `Ident`s.
1085#[derive(Clone)]
1086pub struct Literal {
1087    inner: imp::Literal,
1088    _marker: ProcMacroAutoTraits,
1089}
1090
1091macro_rules! suffixed_int_literals {
1092    ($($name:ident => $kind:ident,)*) => ($(
1093        /// Creates a new suffixed integer literal with the specified value.
1094        ///
1095        /// This function will create an integer like `1u32` where the integer
1096        /// value specified is the first part of the token and the integral is
1097        /// also suffixed at the end. Literals created from negative numbers may
1098        /// not survive roundtrips through `TokenStream` or strings and may be
1099        /// broken into two tokens (`-` and positive literal).
1100        ///
1101        /// Literals created through this method have the `Span::call_site()`
1102        /// span by default, which can be configured with the `set_span` method
1103        /// below.
1104        pub fn $name(n: $kind) -> Literal {
1105            Literal::_new(imp::Literal::$name(n))
1106        }
1107    )*)
1108}
1109
1110macro_rules! unsuffixed_int_literals {
1111    ($($name:ident => $kind:ident,)*) => ($(
1112        /// Creates a new unsuffixed integer literal with the specified value.
1113        ///
1114        /// This function will create an integer like `1` where the integer
1115        /// value specified is the first part of the token. No suffix is
1116        /// specified on this token, meaning that invocations like
1117        /// `Literal::i8_unsuffixed(1)` are equivalent to
1118        /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
1119        /// may not survive roundtrips through `TokenStream` or strings and may
1120        /// be broken into two tokens (`-` and positive literal).
1121        ///
1122        /// Literals created through this method have the `Span::call_site()`
1123        /// span by default, which can be configured with the `set_span` method
1124        /// below.
1125        pub fn $name(n: $kind) -> Literal {
1126            Literal::_new(imp::Literal::$name(n))
1127        }
1128    )*)
1129}
1130
1131impl Literal {
1132    fn _new(inner: imp::Literal) -> Self {
1133        Literal {
1134            inner,
1135            _marker: MARKER,
1136        }
1137    }
1138
1139    fn _new_fallback(inner: fallback::Literal) -> Self {
1140        Literal {
1141            inner: inner.into(),
1142            _marker: MARKER,
1143        }
1144    }
1145
1146    suffixed_int_literals! {
1147        u8_suffixed => u8,
1148        u16_suffixed => u16,
1149        u32_suffixed => u32,
1150        u64_suffixed => u64,
1151        u128_suffixed => u128,
1152        usize_suffixed => usize,
1153        i8_suffixed => i8,
1154        i16_suffixed => i16,
1155        i32_suffixed => i32,
1156        i64_suffixed => i64,
1157        i128_suffixed => i128,
1158        isize_suffixed => isize,
1159    }
1160
1161    unsuffixed_int_literals! {
1162        u8_unsuffixed => u8,
1163        u16_unsuffixed => u16,
1164        u32_unsuffixed => u32,
1165        u64_unsuffixed => u64,
1166        u128_unsuffixed => u128,
1167        usize_unsuffixed => usize,
1168        i8_unsuffixed => i8,
1169        i16_unsuffixed => i16,
1170        i32_unsuffixed => i32,
1171        i64_unsuffixed => i64,
1172        i128_unsuffixed => i128,
1173        isize_unsuffixed => isize,
1174    }
1175
1176    /// Creates a new unsuffixed floating-point literal.
1177    ///
1178    /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1179    /// the float's value is emitted directly into the token but no suffix is
1180    /// used, so it may be inferred to be a `f64` later in the compiler.
1181    /// Literals created from negative numbers may not survive round-trips
1182    /// through `TokenStream` or strings and may be broken into two tokens (`-`
1183    /// and positive literal).
1184    ///
1185    /// # Panics
1186    ///
1187    /// This function requires that the specified float is finite, for example
1188    /// if it is infinity or NaN this function will panic.
1189    pub fn f64_unsuffixed(f: f64) -> Literal {
1190        assert!(f.is_finite());
1191        Literal::_new(imp::Literal::f64_unsuffixed(f))
1192    }
1193
1194    /// Creates a new suffixed floating-point literal.
1195    ///
1196    /// This constructor will create a literal like `1.0f64` where the value
1197    /// specified is the preceding part of the token and `f64` is the suffix of
1198    /// the token. This token will always be inferred to be an `f64` in the
1199    /// compiler. Literals created from negative numbers may not survive
1200    /// round-trips through `TokenStream` or strings and may be broken into two
1201    /// tokens (`-` and positive literal).
1202    ///
1203    /// # Panics
1204    ///
1205    /// This function requires that the specified float is finite, for example
1206    /// if it is infinity or NaN this function will panic.
1207    pub fn f64_suffixed(f: f64) -> Literal {
1208        assert!(f.is_finite());
1209        Literal::_new(imp::Literal::f64_suffixed(f))
1210    }
1211
1212    /// Creates a new unsuffixed floating-point literal.
1213    ///
1214    /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1215    /// the float's value is emitted directly into the token but no suffix is
1216    /// used, so it may be inferred to be a `f64` later in the compiler.
1217    /// Literals created from negative numbers may not survive round-trips
1218    /// through `TokenStream` or strings and may be broken into two tokens (`-`
1219    /// and positive literal).
1220    ///
1221    /// # Panics
1222    ///
1223    /// This function requires that the specified float is finite, for example
1224    /// if it is infinity or NaN this function will panic.
1225    pub fn f32_unsuffixed(f: f32) -> Literal {
1226        assert!(f.is_finite());
1227        Literal::_new(imp::Literal::f32_unsuffixed(f))
1228    }
1229
1230    /// Creates a new suffixed floating-point literal.
1231    ///
1232    /// This constructor will create a literal like `1.0f32` where the value
1233    /// specified is the preceding part of the token and `f32` is the suffix of
1234    /// the token. This token will always be inferred to be an `f32` in the
1235    /// compiler. Literals created from negative numbers may not survive
1236    /// round-trips through `TokenStream` or strings and may be broken into two
1237    /// tokens (`-` and positive literal).
1238    ///
1239    /// # Panics
1240    ///
1241    /// This function requires that the specified float is finite, for example
1242    /// if it is infinity or NaN this function will panic.
1243    pub fn f32_suffixed(f: f32) -> Literal {
1244        assert!(f.is_finite());
1245        Literal::_new(imp::Literal::f32_suffixed(f))
1246    }
1247
1248    /// String literal.
1249    pub fn string(string: &str) -> Literal {
1250        Literal::_new(imp::Literal::string(string))
1251    }
1252
1253    /// Character literal.
1254    pub fn character(ch: char) -> Literal {
1255        Literal::_new(imp::Literal::character(ch))
1256    }
1257
1258    /// Byte character literal.
1259    pub fn byte_character(byte: u8) -> Literal {
1260        Literal::_new(imp::Literal::byte_character(byte))
1261    }
1262
1263    /// Byte string literal.
1264    pub fn byte_string(bytes: &[u8]) -> Literal {
1265        Literal::_new(imp::Literal::byte_string(bytes))
1266    }
1267
1268    /// C string literal.
1269    pub fn c_string(string: &CStr) -> Literal {
1270        Literal::_new(imp::Literal::c_string(string))
1271    }
1272
1273    /// Returns the span encompassing this literal.
1274    pub fn span(&self) -> Span {
1275        Span::_new(self.inner.span())
1276    }
1277
1278    /// Configures the span associated for this literal.
1279    pub fn set_span(&mut self, span: Span) {
1280        self.inner.set_span(span.inner);
1281    }
1282
1283    /// Returns a `Span` that is a subset of `self.span()` containing only
1284    /// the source bytes in range `range`. Returns `None` if the would-be
1285    /// trimmed span is outside the bounds of `self`.
1286    ///
1287    /// Warning: the underlying [`proc_macro::Literal::subspan`] method is
1288    /// nightly-only. When called from within a procedural macro not using a
1289    /// nightly compiler, this method will always return `None`.
1290    ///
1291    /// [`proc_macro::Literal::subspan`]: https://doc.rust-lang.org/proc_macro/struct.Literal.html#method.subspan
1292    pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1293        self.inner.subspan(range).map(Span::_new)
1294    }
1295
1296    // Intended for the `quote!` macro to use when constructing a proc-macro2
1297    // token out of a macro_rules $:literal token, which is already known to be
1298    // a valid literal. This avoids reparsing/validating the literal's string
1299    // representation. This is not public API other than for quote.
1300    #[doc(hidden)]
1301    pub unsafe fn from_str_unchecked(repr: &str) -> Self {
1302        Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })
1303    }
1304}
1305
1306impl FromStr for Literal {
1307    type Err = LexError;
1308
1309    fn from_str(repr: &str) -> Result<Self, LexError> {
1310        repr.parse().map(Literal::_new).map_err(|inner| LexError {
1311            inner,
1312            _marker: MARKER,
1313        })
1314    }
1315}
1316
1317impl Debug for Literal {
1318    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1319        Debug::fmt(&self.inner, f)
1320    }
1321}
1322
1323impl Display for Literal {
1324    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1325        Display::fmt(&self.inner, f)
1326    }
1327}
1328
1329/// Public implementation details for the `TokenStream` type, such as iterators.
1330pub mod token_stream {
1331    use crate::marker::{ProcMacroAutoTraits, MARKER};
1332    use crate::{imp, TokenTree};
1333    use core::fmt::{self, Debug};
1334
1335    pub use crate::TokenStream;
1336
1337    /// An iterator over `TokenStream`'s `TokenTree`s.
1338    ///
1339    /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1340    /// delimited groups, and returns whole groups as token trees.
1341    #[derive(Clone)]
1342    pub struct IntoIter {
1343        inner: imp::TokenTreeIter,
1344        _marker: ProcMacroAutoTraits,
1345    }
1346
1347    impl Iterator for IntoIter {
1348        type Item = TokenTree;
1349
1350        fn next(&mut self) -> Option<TokenTree> {
1351            self.inner.next()
1352        }
1353
1354        fn size_hint(&self) -> (usize, Option<usize>) {
1355            self.inner.size_hint()
1356        }
1357    }
1358
1359    impl Debug for IntoIter {
1360        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1361            f.write_str("TokenStream ")?;
1362            f.debug_list().entries(self.clone()).finish()
1363        }
1364    }
1365
1366    impl IntoIterator for TokenStream {
1367        type Item = TokenTree;
1368        type IntoIter = IntoIter;
1369
1370        fn into_iter(self) -> IntoIter {
1371            IntoIter {
1372                inner: self.inner.into_iter(),
1373                _marker: MARKER,
1374            }
1375        }
1376    }
1377}