Debian Codegraph @

third_party/rust/proc-macro2/src/lib.rs

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