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