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