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//! - **Bring proc-macro-like functionality to other contexts like build.rs and
13//! main.rs.** Types from `proc_macro` are entirely specific to procedural
14//! macros and cannot ever exist in code outside of a procedural macro.
15//! Meanwhile `proc_macro2` types may exist anywhere including non-macro code.
16//! By developing foundational libraries like [syn] and [quote] against
17//! `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem
18//! becomes easily applicable to many other use cases and we avoid
19//! reimplementing non-macro equivalents of those libraries.
20//!
21//! - **Make procedural macros unit testable.** As a consequence of being
22//! specific to procedural macros, nothing that uses `proc_macro` can be
23//! executed from a unit test. In order for helper libraries or components of
24//! a macro to be testable in isolation, they must be implemented using
25//! `proc_macro2`.
26//!
27//! [syn]: https://github.com/dtolnay/syn
28//! [quote]: https://github.com/dtolnay/quote
29//!
30//! # Usage
31//!
32//! The skeleton of a typical procedural macro typically looks like this:
33//!
34//! ```
35//! extern crate proc_macro;
36//!
37//! # const IGNORE: &str = stringify! {
38//! #[proc_macro_derive(MyDerive)]
39//! # };
40//! # #[cfg(wrap_proc_macro)]
41//! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
42//! let input = proc_macro2::TokenStream::from(input);
43//!
44//! let output: proc_macro2::TokenStream = {
45//! /* transform input */
46//! # input
47//! };
48//!
49//! proc_macro::TokenStream::from(output)
50//! }
51//! ```
52//!
53//! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to
54//! propagate parse errors correctly back to the compiler when parsing fails.
55//!
56//! [`parse_macro_input!`]: https://docs.rs/syn/2.0/syn/macro.parse_macro_input.html
57//!
58//! # Unstable features
59//!
60//! The default feature set of proc-macro2 tracks the most recent stable
61//! compiler API. Functionality in `proc_macro` that is not yet stable is not
62//! exposed by proc-macro2 by default.
63//!
64//! To opt into the additional APIs available in the most recent nightly
65//! compiler, the `procmacro2_semver_exempt` config flag must be passed to
66//! rustc. We will polyfill those nightly-only APIs back to Rust 1.68.0. As
67//! these are unstable APIs that track the nightly compiler, minor versions of
68//! proc-macro2 may make breaking changes to them at any time.
69//!
70//! ```sh
71//! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build
72//! ```
73//!
74//! Note that this must not only be done for your crate, but for any crate that
75//! depends on your crate. This infectious nature is intentional, as it serves
76//! as a reminder that you are outside of the normal semver guarantees.
77//!
78//! Semver exempt methods are marked as such in the proc-macro2 documentation.
79//!
80//! # Thread-Safety
81//!
82//! Most types in this crate are `!Sync` because the underlying compiler
83//! types make use of thread-local memory, meaning they cannot be accessed from
84//! a different thread.
8586#![no_std]
87#![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.105")]
88#![cfg_attr(any(proc_macro_span, super_unstable), feature(proc_macro_span))]
89#![cfg_attr(super_unstable, feature(proc_macro_def_site))]
90#![cfg_attr(docsrs, feature(doc_cfg))]
91#![deny(unsafe_op_in_unsafe_fn)]
92#![allow(
93 clippy::cast_lossless,
94 clippy::cast_possible_truncation,
95 clippy::checked_conversions,
96 clippy::doc_markdown,
97 clippy::elidable_lifetime_names,
98 clippy::incompatible_msrv,
99 clippy::items_after_statements,
100 clippy::iter_without_into_iter,
101 clippy::let_underscore_untyped,
102 clippy::manual_assert,
103 clippy::manual_range_contains,
104 clippy::missing_panics_doc,
105 clippy::missing_safety_doc,
106 clippy::must_use_candidate,
107 clippy::needless_doctest_main,
108 clippy::needless_lifetimes,
109 clippy::new_without_default,
110 clippy::return_self_not_must_use,
111 clippy::shadow_unrelated,
112 clippy::trivially_copy_pass_by_ref,
113 clippy::uninlined_format_args,
114 clippy::unnecessary_wraps,
115 clippy::unused_self,
116 clippy::used_underscore_binding,
117 clippy::vec_init_then_push
118)]
119#![allow(unknown_lints, mismatched_lifetime_syntaxes)]
120121#[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))]
122compile_error! {"\
123 Something is not right. If you've tried to turn on \
124 procmacro2_semver_exempt, you need to ensure that it \
125 is turned on for the compilation of the proc-macro2 \
126 build script as well.
127"}
128129#[cfg(all(
130 procmacro2_nightly_testing,
131 feature = "proc-macro",
132 not(proc_macro_span)
133))]
134compile_error! {"\
135 Build script probe failed to compile.
136"}
137138extern crate alloc;
139extern crate std;
140141#[cfg(feature = "proc-macro")]
142extern crate proc_macro;
143144mod marker;
145mod parse;
146mod probe;
147mod rcvec;
148149#[cfg(wrap_proc_macro)]
150mod detection;
151152// Public for proc_macro2::fallback::force() and unforce(), but those are quite
153// a niche use case so we omit it from rustdoc.
154#[doc(hidden)]
155pub mod fallback;
156157pub mod extra;
158159#[cfg(not(wrap_proc_macro))]
160use crate::fallback as imp;
161#[path = "wrapper.rs"]
162#[cfg(wrap_proc_macro)]
163mod imp;
164165#[cfg(span_locations)]
166mod location;
167168#[cfg(procmacro2_semver_exempt)]
169mod num;
170#[cfg(procmacro2_semver_exempt)]
171#[allow(dead_code)]
172mod rustc_literal_escaper;
173174use crate::extra::DelimSpan;
175use crate::marker::{ProcMacroAutoTraits, MARKER};
176#[cfg(procmacro2_semver_exempt)]
177use crate::rustc_literal_escaper::MixedUnit;
178#[cfg(procmacro2_semver_exempt)]
179use alloc::borrow::ToOwnedas _;
180use alloc::string::{String, ToStringas _};
181#[cfg(procmacro2_semver_exempt)]
182use alloc::vec::Vec;
183use core::cmp::Ordering;
184use core::ffi::CStr;
185use core::fmt::{self, Debug, Display};
186use core::hash::{Hash, Hasher};
187#[cfg(span_locations)]
188use core::ops::Range;
189use core::ops::RangeBounds;
190use core::str::FromStr;
191use std::error::Error;
192#[cfg(span_locations)]
193use std::path::PathBuf;
194195#[cfg(span_locations)]
196#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
197pub use crate::location::LineColumn;
198199#[cfg(procmacro2_semver_exempt)]
200#[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
201pub use crate::rustc_literal_escaper::EscapeError;
202203/// An abstract stream of tokens, or more concretely a sequence of token trees.
204///
205/// This type provides interfaces for iterating over token trees and for
206/// collecting token trees into one stream.
207///
208/// Token stream is both the input and output of `#[proc_macro]`,
209/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
210#[derive(#[automatically_derived]
impl ::core::clone::Clone for TokenStream {
#[inline]
fn clone(&self) -> TokenStream {
TokenStream {
inner: ::core::clone::Clone::clone(&self.inner),
_marker: ::core::clone::Clone::clone(&self._marker),
}
}
}Clone)]
211pub struct TokenStream {
212 inner: imp::TokenStream,
213 _marker: ProcMacroAutoTraits,
214}
215216/// Error returned from `TokenStream::from_str`.
217pub struct LexError {
218 inner: imp::LexError,
219 _marker: ProcMacroAutoTraits,
220}
221222impl TokenStream {
223fn _new(inner: imp::TokenStream) -> Self {
224TokenStream {
225inner,
226 _marker: MARKER,
227 }
228 }
229230fn _new_fallback(inner: fallback::TokenStream) -> Self {
231TokenStream {
232 inner: imp::TokenStream::from(inner),
233 _marker: MARKER,
234 }
235 }
236237/// Returns an empty `TokenStream` containing no token trees.
238pub fn new() -> Self {
239TokenStream::_new(imp::TokenStream::new())
240 }
241242/// Checks if this `TokenStream` is empty.
243pub fn is_empty(&self) -> bool {
244self.inner.is_empty()
245 }
246}
247248/// `TokenStream::default()` returns an empty stream,
249/// i.e. this is equivalent with `TokenStream::new()`.
250impl Defaultfor TokenStream {
251fn default() -> Self {
252TokenStream::new()
253 }
254}
255256/// Attempts to break the string into tokens and parse those tokens into a token
257/// stream.
258///
259/// May fail for a number of reasons, for example, if the string contains
260/// unbalanced delimiters or characters not existing in the language.
261///
262/// NOTE: Some errors may cause panics instead of returning `LexError`. We
263/// reserve the right to change these errors into `LexError`s later.
264impl FromStrfor TokenStream {
265type Err = LexError;
266267fn from_str(src: &str) -> Result<TokenStream, LexError> {
268match imp::TokenStream::from_str_checked(src) {
269Ok(tokens) => Ok(TokenStream::_new(tokens)),
270Err(lex) => Err(LexError {
271 inner: lex,
272 _marker: MARKER,
273 }),
274 }
275 }
276}
277278#[cfg(feature = "proc-macro")]
279#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
280impl From<proc_macro::TokenStream> for TokenStream {
281fn from(inner: proc_macro::TokenStream) -> Self {
282TokenStream::_new(imp::TokenStream::from(inner))
283 }
284}
285286#[cfg(feature = "proc-macro")]
287#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
288impl From<TokenStream> for proc_macro::TokenStream {
289fn from(inner: TokenStream) -> Self {
290 proc_macro::TokenStream::from(inner.inner)
291 }
292}
293294impl From<TokenTree> for TokenStream {
295fn from(token: TokenTree) -> Self {
296TokenStream::_new(imp::TokenStream::from(token))
297 }
298}
299300impl Extend<TokenTree> for TokenStream {
301fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, tokens: I) {
302self.inner.extend(tokens);
303 }
304}
305306impl Extend<TokenStream> for TokenStream {
307fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
308self.inner
309 .extend(streams.into_iter().map(|stream| stream.inner));
310 }
311}
312313impl Extend<Group> for TokenStream {
314fn extend<I: IntoIterator<Item = Group>>(&mut self, tokens: I) {
315self.inner.extend(tokens.into_iter().map(TokenTree::Group));
316 }
317}
318319impl Extend<Ident> for TokenStream {
320fn extend<I: IntoIterator<Item = Ident>>(&mut self, tokens: I) {
321self.inner.extend(tokens.into_iter().map(TokenTree::Ident));
322 }
323}
324325impl Extend<Punct> for TokenStream {
326fn extend<I: IntoIterator<Item = Punct>>(&mut self, tokens: I) {
327self.inner.extend(tokens.into_iter().map(TokenTree::Punct));
328 }
329}
330331impl Extend<Literal> for TokenStream {
332fn extend<I: IntoIterator<Item = Literal>>(&mut self, tokens: I) {
333self.inner
334 .extend(tokens.into_iter().map(TokenTree::Literal));
335 }
336}
337338/// Collects a number of token trees into a single stream.
339impl FromIterator<TokenTree> for TokenStream {
340fn from_iter<I: IntoIterator<Item = TokenTree>>(tokens: I) -> Self {
341TokenStream::_new(tokens.into_iter().collect())
342 }
343}
344345impl FromIterator<TokenStream> for TokenStream {
346fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
347TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
348 }
349}
350351/// Prints the token stream as a string that is supposed to be losslessly
352/// convertible back into the same token stream (modulo spans), except for
353/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
354/// numeric literals.
355impl Displayfor TokenStream {
356fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
357 Display::fmt(&self.inner, f)
358 }
359}
360361/// Prints token in a form convenient for debugging.
362impl Debugfor TokenStream {
363fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
364 Debug::fmt(&self.inner, f)
365 }
366}
367368impl LexError {
369pub fn span(&self) -> Span {
370Span::_new(self.inner.span())
371 }
372}
373374impl Debugfor LexError {
375fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
376 Debug::fmt(&self.inner, f)
377 }
378}
379380impl Displayfor LexError {
381fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
382 Display::fmt(&self.inner, f)
383 }
384}
385386impl Errorfor LexError {}
387388/// A region of source code, along with macro expansion information.
389#[derive(#[automatically_derived]
impl ::core::marker::Copy for Span { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Span {
#[inline]
fn clone(&self) -> Span {
let _: ::core::clone::AssertParamIsClone<imp::Span>;
let _: ::core::clone::AssertParamIsClone<ProcMacroAutoTraits>;
*self
}
}Clone)]
390pub struct Span {
391 inner: imp::Span,
392 _marker: ProcMacroAutoTraits,
393}
394395impl Span {
396fn _new(inner: imp::Span) -> Self {
397Span {
398inner,
399 _marker: MARKER,
400 }
401 }
402403fn _new_fallback(inner: fallback::Span) -> Self {
404Span {
405 inner: imp::Span::from(inner),
406 _marker: MARKER,
407 }
408 }
409410/// The span of the invocation of the current procedural macro.
411 ///
412 /// Identifiers created with this span will be resolved as if they were
413 /// written directly at the macro call location (call-site hygiene) and
414 /// other code at the macro call site will be able to refer to them as well.
415pub fn call_site() -> Self {
416Span::_new(imp::Span::call_site())
417 }
418419/// The span located at the invocation of the procedural macro, but with
420 /// local variables, labels, and `$crate` resolved at the definition site
421 /// of the macro. This is the same hygiene behavior as `macro_rules`.
422pub fn mixed_site() -> Self {
423Span::_new(imp::Span::mixed_site())
424 }
425426/// A span that resolves at the macro definition site.
427 ///
428 /// This method is semver exempt and not exposed by default.
429#[cfg(procmacro2_semver_exempt)]
430 #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
431pub fn def_site() -> Self {
432Span::_new(imp::Span::def_site())
433 }
434435/// Creates a new span with the same line/column information as `self` but
436 /// that resolves symbols as though it were at `other`.
437pub fn resolved_at(&self, other: Span) -> Span {
438Span::_new(self.inner.resolved_at(other.inner))
439 }
440441/// Creates a new span with the same name resolution behavior as `self` but
442 /// with the line/column information of `other`.
443pub fn located_at(&self, other: Span) -> Span {
444Span::_new(self.inner.located_at(other.inner))
445 }
446447/// Convert `proc_macro2::Span` to `proc_macro::Span`.
448 ///
449 /// This method is available when building with a nightly compiler, or when
450 /// building with rustc 1.29+ *without* semver exempt features.
451 ///
452 /// # Panics
453 ///
454 /// Panics if called from outside of a procedural macro. Unlike
455 /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
456 /// the context of a procedural macro invocation.
457#[cfg(wrap_proc_macro)]
458pub fn unwrap(self) -> proc_macro::Span {
459self.inner.unwrap()
460 }
461462// Soft deprecated. Please use Span::unwrap.
463#[cfg(wrap_proc_macro)]
464 #[doc(hidden)]
465pub fn unstable(self) -> proc_macro::Span {
466self.unwrap()
467 }
468469/// Returns the span's byte position range in the source file.
470 ///
471 /// This method requires the `"span-locations"` feature to be enabled.
472 ///
473 /// When executing in a procedural macro context, the returned range is only
474 /// accurate if compiled with a nightly toolchain. The stable toolchain does
475 /// not have this information available. When executing outside of a
476 /// procedural macro, such as main.rs or build.rs, the byte range is always
477 /// accurate regardless of toolchain.
478#[cfg(span_locations)]
479 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
480pub fn byte_range(&self) -> Range<usize> {
481self.inner.byte_range()
482 }
483484/// Get the starting line/column in the source file for this span.
485 ///
486 /// This method requires the `"span-locations"` feature to be enabled.
487 ///
488 /// When executing in a procedural macro context, the returned line/column
489 /// are only meaningful if compiled with a nightly toolchain. The stable
490 /// toolchain does not have this information available. When executing
491 /// outside of a procedural macro, such as main.rs or build.rs, the
492 /// line/column are always meaningful regardless of toolchain.
493#[cfg(span_locations)]
494 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
495pub fn start(&self) -> LineColumn {
496self.inner.start()
497 }
498499/// Get the ending line/column in the source file for this span.
500 ///
501 /// This method requires the `"span-locations"` feature to be enabled.
502 ///
503 /// When executing in a procedural macro context, the returned line/column
504 /// are only meaningful if compiled with a nightly toolchain. The stable
505 /// toolchain does not have this information available. When executing
506 /// outside of a procedural macro, such as main.rs or build.rs, the
507 /// line/column are always meaningful regardless of toolchain.
508#[cfg(span_locations)]
509 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
510pub fn end(&self) -> LineColumn {
511self.inner.end()
512 }
513514/// The path to the source file in which this span occurs, for display
515 /// purposes.
516 ///
517 /// This might not correspond to a valid file system path. It might be
518 /// remapped, or might be an artificial path such as `"<macro expansion>"`.
519#[cfg(span_locations)]
520 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
521pub fn file(&self) -> String {
522self.inner.file()
523 }
524525/// The path to the source file in which this span occurs on disk.
526 ///
527 /// This is the actual path on disk. It is unaffected by path remapping.
528 ///
529 /// This path should not be embedded in the output of the macro; prefer
530 /// `file()` instead.
531#[cfg(span_locations)]
532 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
533pub fn local_file(&self) -> Option<PathBuf> {
534self.inner.local_file()
535 }
536537/// Create a new span encompassing `self` and `other`.
538 ///
539 /// Returns `None` if `self` and `other` are from different files.
540 ///
541 /// Warning: the underlying [`proc_macro::Span::join`] method is
542 /// nightly-only. When called from within a procedural macro not using a
543 /// nightly compiler, this method will always return `None`.
544pub fn join(&self, other: Span) -> Option<Span> {
545self.inner.join(other.inner).map(Span::_new)
546 }
547548/// Compares two spans to see if they're equal.
549 ///
550 /// This method is semver exempt and not exposed by default.
551#[cfg(procmacro2_semver_exempt)]
552 #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
553pub fn eq(&self, other: &Span) -> bool {
554self.inner.eq(&other.inner)
555 }
556557/// Returns the source text behind a span. This preserves the original
558 /// source code, including spaces and comments. It only returns a result if
559 /// the span corresponds to real source code.
560 ///
561 /// Note: The observable result of a macro should only rely on the tokens
562 /// and not on this source text. The result of this function is a best
563 /// effort to be used for diagnostics only.
564pub fn source_text(&self) -> Option<String> {
565self.inner.source_text()
566 }
567}
568569/// Prints a span in a form convenient for debugging.
570impl Debugfor Span {
571fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
572 Debug::fmt(&self.inner, f)
573 }
574}
575576/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
577#[derive(#[automatically_derived]
impl ::core::clone::Clone for TokenTree {
#[inline]
fn clone(&self) -> TokenTree {
match self {
TokenTree::Group(__self_0) =>
TokenTree::Group(::core::clone::Clone::clone(__self_0)),
TokenTree::Ident(__self_0) =>
TokenTree::Ident(::core::clone::Clone::clone(__self_0)),
TokenTree::Punct(__self_0) =>
TokenTree::Punct(::core::clone::Clone::clone(__self_0)),
TokenTree::Literal(__self_0) =>
TokenTree::Literal(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
578pub enum TokenTree {
579/// A token stream surrounded by bracket delimiters.
580Group(Group),
581/// An identifier.
582Ident(Ident),
583/// A single punctuation character (`+`, `,`, `$`, etc.).
584Punct(Punct),
585/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
586Literal(Literal),
587}
588589impl TokenTree {
590/// Returns the span of this tree, delegating to the `span` method of
591 /// the contained token or a delimited stream.
592pub fn span(&self) -> Span {
593match self {
594 TokenTree::Group(t) => t.span(),
595 TokenTree::Ident(t) => t.span(),
596 TokenTree::Punct(t) => t.span(),
597 TokenTree::Literal(t) => t.span(),
598 }
599 }
600601/// Configures the span for *only this token*.
602 ///
603 /// Note that if this token is a `Group` then this method will not configure
604 /// the span of each of the internal tokens, this will simply delegate to
605 /// the `set_span` method of each variant.
606pub fn set_span(&mut self, span: Span) {
607match self {
608 TokenTree::Group(t) => t.set_span(span),
609 TokenTree::Ident(t) => t.set_span(span),
610 TokenTree::Punct(t) => t.set_span(span),
611 TokenTree::Literal(t) => t.set_span(span),
612 }
613 }
614}
615616impl From<Group> for TokenTree {
617fn from(g: Group) -> Self {
618 TokenTree::Group(g)
619 }
620}
621622impl From<Ident> for TokenTree {
623fn from(g: Ident) -> Self {
624 TokenTree::Ident(g)
625 }
626}
627628impl From<Punct> for TokenTree {
629fn from(g: Punct) -> Self {
630 TokenTree::Punct(g)
631 }
632}
633634impl From<Literal> for TokenTree {
635fn from(g: Literal) -> Self {
636 TokenTree::Literal(g)
637 }
638}
639640/// Prints the token tree as a string that is supposed to be losslessly
641/// convertible back into the same token tree (modulo spans), except for
642/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
643/// numeric literals.
644impl Displayfor TokenTree {
645fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
646match self {
647 TokenTree::Group(t) => Display::fmt(t, f),
648 TokenTree::Ident(t) => Display::fmt(t, f),
649 TokenTree::Punct(t) => Display::fmt(t, f),
650 TokenTree::Literal(t) => Display::fmt(t, f),
651 }
652 }
653}
654655/// Prints token tree in a form convenient for debugging.
656impl Debugfor TokenTree {
657fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
658// Each of these has the name in the struct type in the derived debug,
659 // so don't bother with an extra layer of indirection
660match self {
661 TokenTree::Group(t) => Debug::fmt(t, f),
662 TokenTree::Ident(t) => {
663let mut debug = f.debug_struct("Ident");
664debug.field("sym", &format_args!("{0}", t)format_args!("{}", t));
665 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
666debug.finish()
667 }
668 TokenTree::Punct(t) => Debug::fmt(t, f),
669 TokenTree::Literal(t) => Debug::fmt(t, f),
670 }
671 }
672}
673674/// A delimited token stream.
675///
676/// A `Group` internally contains a `TokenStream` which is surrounded by
677/// `Delimiter`s.
678#[derive(#[automatically_derived]
impl ::core::clone::Clone for Group {
#[inline]
fn clone(&self) -> Group {
Group { inner: ::core::clone::Clone::clone(&self.inner) }
}
}Clone)]
679pub struct Group {
680 inner: imp::Group,
681}
682683/// Describes how a sequence of token trees is delimited.
684#[derive(#[automatically_derived]
impl ::core::marker::Copy for Delimiter { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Delimiter {
#[inline]
fn clone(&self) -> Delimiter { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Delimiter {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Delimiter::Parenthesis => "Parenthesis",
Delimiter::Brace => "Brace",
Delimiter::Bracket => "Bracket",
Delimiter::None => "None",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for Delimiter {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) -> () {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for Delimiter {
#[inline]
fn eq(&self, other: &Delimiter) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
685pub enum Delimiter {
686/// `( ... )`
687Parenthesis,
688/// `{ ... }`
689Brace,
690/// `[ ... ]`
691Bracket,
692/// `∅ ... ∅`
693 ///
694 /// An invisible delimiter, that may, for example, appear around tokens
695 /// coming from a "macro variable" `$var`. It is important to preserve
696 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
697 /// Invisible delimiters may not survive roundtrip of a token stream through
698 /// a string.
699 ///
700 /// <div class="warning">
701 ///
702 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
703 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
704 /// of a proc_macro macro are preserved, and only in very specific circumstances.
705 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
706 /// operator priorities as indicated above. The other `Delimiter` variants should be used
707 /// instead in this context. This is a rustc bug. For details, see
708 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
709 ///
710 /// </div>
711None,
712}
713714impl Group {
715fn _new(inner: imp::Group) -> Self {
716Group { inner }
717 }
718719fn _new_fallback(inner: fallback::Group) -> Self {
720Group {
721 inner: imp::Group::from(inner),
722 }
723 }
724725/// Creates a new `Group` with the given delimiter and token stream.
726 ///
727 /// This constructor will set the span for this group to
728 /// `Span::call_site()`. To change the span you can use the `set_span`
729 /// method below.
730pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
731Group {
732 inner: imp::Group::new(delimiter, stream.inner),
733 }
734 }
735736/// Returns the punctuation used as the delimiter for this group: a set of
737 /// parentheses, square brackets, or curly braces.
738pub fn delimiter(&self) -> Delimiter {
739self.inner.delimiter()
740 }
741742/// Returns the `TokenStream` of tokens that are delimited in this `Group`.
743 ///
744 /// Note that the returned token stream does not include the delimiter
745 /// returned above.
746pub fn stream(&self) -> TokenStream {
747TokenStream::_new(self.inner.stream())
748 }
749750/// Returns the span for the delimiters of this token stream, spanning the
751 /// entire `Group`.
752 ///
753 /// ```text
754 /// pub fn span(&self) -> Span {
755 /// ^^^^^^^
756 /// ```
757pub fn span(&self) -> Span {
758Span::_new(self.inner.span())
759 }
760761/// Returns the span pointing to the opening delimiter of this group.
762 ///
763 /// ```text
764 /// pub fn span_open(&self) -> Span {
765 /// ^
766 /// ```
767pub fn span_open(&self) -> Span {
768Span::_new(self.inner.span_open())
769 }
770771/// Returns the span pointing to the closing delimiter of this group.
772 ///
773 /// ```text
774 /// pub fn span_close(&self) -> Span {
775 /// ^
776 /// ```
777pub fn span_close(&self) -> Span {
778Span::_new(self.inner.span_close())
779 }
780781/// Returns an object that holds this group's `span_open()` and
782 /// `span_close()` together (in a more compact representation than holding
783 /// those 2 spans individually).
784pub fn delim_span(&self) -> DelimSpan {
785DelimSpan::new(&self.inner)
786 }
787788/// Configures the span for this `Group`'s delimiters, but not its internal
789 /// tokens.
790 ///
791 /// This method will **not** set the span of all the internal tokens spanned
792 /// by this group, but rather it will only set the span of the delimiter
793 /// tokens at the level of the `Group`.
794pub fn set_span(&mut self, span: Span) {
795self.inner.set_span(span.inner);
796 }
797}
798799/// Prints the group as a string that should be losslessly convertible back
800/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
801/// with `Delimiter::None` delimiters.
802impl Displayfor Group {
803fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
804 Display::fmt(&self.inner, formatter)
805 }
806}
807808impl Debugfor Group {
809fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
810 Debug::fmt(&self.inner, formatter)
811 }
812}
813814/// A `Punct` is a single punctuation character like `+`, `-` or `#`.
815///
816/// Multicharacter operators like `+=` are represented as two instances of
817/// `Punct` with different forms of `Spacing` returned.
818#[derive(#[automatically_derived]
impl ::core::clone::Clone for Punct {
#[inline]
fn clone(&self) -> Punct {
Punct {
ch: ::core::clone::Clone::clone(&self.ch),
spacing: ::core::clone::Clone::clone(&self.spacing),
span: ::core::clone::Clone::clone(&self.span),
}
}
}Clone)]
819pub struct Punct {
820 ch: char,
821 spacing: Spacing,
822 span: Span,
823}
824825/// Whether a `Punct` is followed immediately by another `Punct` or followed by
826/// another token or whitespace.
827#[derive(#[automatically_derived]
impl ::core::marker::Copy for Spacing { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Spacing {
#[inline]
fn clone(&self) -> Spacing { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Spacing {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Spacing::Alone => "Alone",
Spacing::Joint => "Joint",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for Spacing {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) -> () {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for Spacing {
#[inline]
fn eq(&self, other: &Spacing) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
828pub enum Spacing {
829/// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
830Alone,
831/// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.
832 ///
833 /// Additionally, single quote `'` can join with identifiers to form
834 /// lifetimes `'ident`.
835Joint,
836}
837838impl Punct {
839/// Creates a new `Punct` from the given character and spacing.
840 ///
841 /// The `ch` argument must be a valid punctuation character permitted by the
842 /// language, otherwise the function will panic.
843 ///
844 /// The returned `Punct` will have the default span of `Span::call_site()`
845 /// which can be further configured with the `set_span` method below.
846pub fn new(ch: char, spacing: Spacing) -> Self {
847if let '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';'
848| '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch849 {
850Punct {
851ch,
852spacing,
853 span: Span::call_site(),
854 }
855 } else {
856{
::core::panicking::panic_fmt(format_args!("unsupported proc macro punctuation character {0:?}",
ch));
};panic!("unsupported proc macro punctuation character {:?}", ch);
857 }
858 }
859860/// Returns the value of this punctuation character as `char`.
861pub fn as_char(&self) -> char {
862self.ch
863 }
864865/// Returns the spacing of this punctuation character, indicating whether
866 /// it's immediately followed by another `Punct` in the token stream, so
867 /// they can potentially be combined into a multicharacter operator
868 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
869 /// so the operator has certainly ended.
870pub fn spacing(&self) -> Spacing {
871self.spacing
872 }
873874/// Returns the span for this punctuation character.
875pub fn span(&self) -> Span {
876self.span
877 }
878879/// Configure the span for this punctuation character.
880pub fn set_span(&mut self, span: Span) {
881self.span = span;
882 }
883}
884885/// Prints the punctuation character as a string that should be losslessly
886/// convertible back into the same character.
887impl Displayfor Punct {
888fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
889 Display::fmt(&self.ch, f)
890 }
891}
892893impl Debugfor Punct {
894fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
895let mut debug = fmt.debug_struct("Punct");
896debug.field("char", &self.ch);
897debug.field("spacing", &self.spacing);
898 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
899debug.finish()
900 }
901}
902903/// A word of Rust code, which may be a keyword or legal variable name.
904///
905/// An identifier consists of at least one Unicode code point, the first of
906/// which has the XID_Start property and the rest of which have the XID_Continue
907/// property.
908///
909/// - The empty string is not an identifier. Use `Option<Ident>`.
910/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
911///
912/// An identifier constructed with `Ident::new` is permitted to be a Rust
913/// keyword, though parsing one through its [`Parse`] implementation rejects
914/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
915/// behaviour of `Ident::new`.
916///
917/// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html
918///
919/// # Examples
920///
921/// A new ident can be created from a string using the `Ident::new` function.
922/// A span must be provided explicitly which governs the name resolution
923/// behavior of the resulting identifier.
924///
925/// ```
926/// use proc_macro2::{Ident, Span};
927///
928/// fn main() {
929/// let call_ident = Ident::new("calligraphy", Span::call_site());
930///
931/// println!("{}", call_ident);
932/// }
933/// ```
934///
935/// An ident can be interpolated into a token stream using the `quote!` macro.
936///
937/// ```
938/// use proc_macro2::{Ident, Span};
939/// use quote::quote;
940///
941/// fn main() {
942/// let ident = Ident::new("demo", Span::call_site());
943///
944/// // Create a variable binding whose name is this ident.
945/// let expanded = quote! { let #ident = 10; };
946///
947/// // Create a variable binding with a slightly different name.
948/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
949/// let expanded = quote! { let #temp_ident = 10; };
950/// }
951/// ```
952///
953/// A string representation of the ident is available through the `to_string()`
954/// method.
955///
956/// ```
957/// # use proc_macro2::{Ident, Span};
958/// #
959/// # let ident = Ident::new("another_identifier", Span::call_site());
960/// #
961/// // Examine the ident as a string.
962/// let ident_string = ident.to_string();
963/// if ident_string.len() > 60 {
964/// println!("Very long identifier: {}", ident_string)
965/// }
966/// ```
967#[derive(#[automatically_derived]
impl ::core::clone::Clone for Ident {
#[inline]
fn clone(&self) -> Ident {
Ident {
inner: ::core::clone::Clone::clone(&self.inner),
_marker: ::core::clone::Clone::clone(&self._marker),
}
}
}Clone)]
968pub struct Ident {
969 inner: imp::Ident,
970 _marker: ProcMacroAutoTraits,
971}
972973impl Ident {
974fn _new(inner: imp::Ident) -> Self {
975Ident {
976inner,
977 _marker: MARKER,
978 }
979 }
980981fn _new_fallback(inner: fallback::Ident) -> Self {
982Ident {
983 inner: imp::Ident::from(inner),
984 _marker: MARKER,
985 }
986 }
987988/// Creates a new `Ident` with the given `string` as well as the specified
989 /// `span`.
990 ///
991 /// The `string` argument must be a valid identifier permitted by the
992 /// language, otherwise the function will panic.
993 ///
994 /// Note that `span`, currently in rustc, configures the hygiene information
995 /// for this identifier.
996 ///
997 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
998 /// hygiene meaning that identifiers created with this span will be resolved
999 /// as if they were written directly at the location of the macro call, and
1000 /// other code at the macro call site will be able to refer to them as well.
1001 ///
1002 /// Later spans like `Span::def_site()` will allow to opt-in to
1003 /// "definition-site" hygiene meaning that identifiers created with this
1004 /// span will be resolved at the location of the macro definition and other
1005 /// code at the macro call site will not be able to refer to them.
1006 ///
1007 /// Due to the current importance of hygiene this constructor, unlike other
1008 /// tokens, requires a `Span` to be specified at construction.
1009 ///
1010 /// # Panics
1011 ///
1012 /// Panics if the input string is neither a keyword nor a legal variable
1013 /// name. If you are not sure whether the string contains an identifier and
1014 /// need to handle an error case, use
1015 /// <a href="https://docs.rs/syn/2.0/syn/fn.parse_str.html"><code
1016 /// style="padding-right:0;">syn::parse_str</code></a><code
1017 /// style="padding-left:0;">::<Ident></code>
1018 /// rather than `Ident::new`.
1019#[track_caller]
1020pub fn new(string: &str, span: Span) -> Self {
1021Ident::_new(imp::Ident::new_checked(string, span.inner))
1022 }
10231024/// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The
1025 /// `string` argument must be a valid identifier permitted by the language
1026 /// (including keywords, e.g. `fn`). Keywords which are usable in path
1027 /// segments (e.g. `self`, `super`) are not supported, and will cause a
1028 /// panic.
1029#[track_caller]
1030pub fn new_raw(string: &str, span: Span) -> Self {
1031Ident::_new(imp::Ident::new_raw_checked(string, span.inner))
1032 }
10331034/// Returns the span of this `Ident`.
1035pub fn span(&self) -> Span {
1036Span::_new(self.inner.span())
1037 }
10381039/// Configures the span of this `Ident`, possibly changing its hygiene
1040 /// context.
1041pub fn set_span(&mut self, span: Span) {
1042self.inner.set_span(span.inner);
1043 }
1044}
10451046impl PartialEqfor Ident {
1047fn eq(&self, other: &Ident) -> bool {
1048self.inner == other.inner
1049 }
1050}
10511052impl<T> PartialEq<T> for Ident1053where
1054T: ?Sized + AsRef<str>,
1055{
1056fn eq(&self, other: &T) -> bool {
1057self.inner == other1058 }
1059}
10601061impl Eqfor Ident {}
10621063impl PartialOrdfor Ident {
1064fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
1065Some(self.cmp(other))
1066 }
1067}
10681069impl Ordfor Ident {
1070fn cmp(&self, other: &Ident) -> Ordering {
1071self.to_string().cmp(&other.to_string())
1072 }
1073}
10741075impl Hashfor Ident {
1076fn hash<H: Hasher>(&self, hasher: &mut H) {
1077self.to_string().hash(hasher);
1078 }
1079}
10801081/// Prints the identifier as a string that should be losslessly convertible back
1082/// into the same identifier.
1083impl Displayfor Ident {
1084fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1085 Display::fmt(&self.inner, f)
1086 }
1087}
10881089impl Debugfor Ident {
1090fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1091 Debug::fmt(&self.inner, f)
1092 }
1093}
10941095/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
1096/// byte character (`b'a'`), an integer or floating point number with or without
1097/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1098///
1099/// Boolean literals like `true` and `false` do not belong here, they are
1100/// `Ident`s.
1101#[derive(#[automatically_derived]
impl ::core::clone::Clone for Literal {
#[inline]
fn clone(&self) -> Literal {
Literal {
inner: ::core::clone::Clone::clone(&self.inner),
_marker: ::core::clone::Clone::clone(&self._marker),
}
}
}Clone)]
1102pub struct Literal {
1103 inner: imp::Literal,
1104 _marker: ProcMacroAutoTraits,
1105}
11061107macro_rules! suffixed_int_literals {
1108 ($($name:ident => $kind:ident,)*) => ($(
1109/// Creates a new suffixed integer literal with the specified value.
1110 ///
1111 /// This function will create an integer like `1u32` where the integer
1112 /// value specified is the first part of the token and the integral is
1113 /// also suffixed at the end. Literals created from negative numbers may
1114 /// not survive roundtrips through `TokenStream` or strings and may be
1115 /// broken into two tokens (`-` and positive literal).
1116 ///
1117 /// Literals created through this method have the `Span::call_site()`
1118 /// span by default, which can be configured with the `set_span` method
1119 /// below.
1120pub fn $name(n: $kind) -> Literal {
1121 Literal::_new(imp::Literal::$name(n))
1122 }
1123 )*)
1124}
11251126macro_rules! unsuffixed_int_literals {
1127 ($($name:ident => $kind:ident,)*) => ($(
1128/// Creates a new unsuffixed integer literal with the specified value.
1129 ///
1130 /// This function will create an integer like `1` where the integer
1131 /// value specified is the first part of the token. No suffix is
1132 /// specified on this token, meaning that invocations like
1133 /// `Literal::i8_unsuffixed(1)` are equivalent to
1134 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
1135 /// may not survive roundtrips through `TokenStream` or strings and may
1136 /// be broken into two tokens (`-` and positive literal).
1137 ///
1138 /// Literals created through this method have the `Span::call_site()`
1139 /// span by default, which can be configured with the `set_span` method
1140 /// below.
1141pub fn $name(n: $kind) -> Literal {
1142 Literal::_new(imp::Literal::$name(n))
1143 }
1144 )*)
1145}
11461147impl Literal {
1148fn _new(inner: imp::Literal) -> Self {
1149Literal {
1150inner,
1151 _marker: MARKER,
1152 }
1153 }
11541155fn _new_fallback(inner: fallback::Literal) -> Self {
1156Literal {
1157 inner: imp::Literal::from(inner),
1158 _marker: MARKER,
1159 }
1160 }
11611162n
Literal
Literal::_new(imp::Literal::isize_suffixed(n));suffixed_int_literals! {
1163 u8_suffixed => u8,
1164 u16_suffixed => u16,
1165 u32_suffixed => u32,
1166 u64_suffixed => u64,
1167 u128_suffixed => u128,
1168 usize_suffixed => usize,
1169 i8_suffixed => i8,
1170 i16_suffixed => i16,
1171 i32_suffixed => i32,
1172 i64_suffixed => i64,
1173 i128_suffixed => i128,
1174 isize_suffixed => isize,
1175 }11761177n
Literal
Literal::_new(imp::Literal::isize_unsuffixed(n));unsuffixed_int_literals! {
1178 u8_unsuffixed => u8,
1179 u16_unsuffixed => u16,
1180 u32_unsuffixed => u32,
1181 u64_unsuffixed => u64,
1182 u128_unsuffixed => u128,
1183 usize_unsuffixed => usize,
1184 i8_unsuffixed => i8,
1185 i16_unsuffixed => i16,
1186 i32_unsuffixed => i32,
1187 i64_unsuffixed => i64,
1188 i128_unsuffixed => i128,
1189 isize_unsuffixed => isize,
1190 }11911192/// Creates a new unsuffixed floating-point literal.
1193 ///
1194 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1195 /// the float's value is emitted directly into the token but no suffix is
1196 /// used, so it may be inferred to be a `f64` later in the compiler.
1197 /// Literals created from negative numbers may not survive round-trips
1198 /// through `TokenStream` or strings and may be broken into two tokens (`-`
1199 /// and positive literal).
1200 ///
1201 /// # Panics
1202 ///
1203 /// This function requires that the specified float is finite, for example
1204 /// if it is infinity or NaN this function will panic.
1205pub fn f64_unsuffixed(f: f64) -> Literal {
1206if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1207Literal::_new(imp::Literal::f64_unsuffixed(f))
1208 }
12091210/// Creates a new suffixed floating-point literal.
1211 ///
1212 /// This constructor will create a literal like `1.0f64` where the value
1213 /// specified is the preceding part of the token and `f64` is the suffix of
1214 /// the token. This token will always be inferred to be an `f64` in the
1215 /// compiler. Literals created from negative numbers may not survive
1216 /// round-trips through `TokenStream` or strings and may be broken into two
1217 /// tokens (`-` and positive literal).
1218 ///
1219 /// # Panics
1220 ///
1221 /// This function requires that the specified float is finite, for example
1222 /// if it is infinity or NaN this function will panic.
1223pub fn f64_suffixed(f: f64) -> Literal {
1224if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1225Literal::_new(imp::Literal::f64_suffixed(f))
1226 }
12271228/// Creates a new unsuffixed floating-point literal.
1229 ///
1230 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1231 /// the float's value is emitted directly into the token but no suffix is
1232 /// used, so it may be inferred to be a `f64` later in the compiler.
1233 /// Literals created from negative numbers may not survive round-trips
1234 /// through `TokenStream` or strings and may be broken into two tokens (`-`
1235 /// and positive literal).
1236 ///
1237 /// # Panics
1238 ///
1239 /// This function requires that the specified float is finite, for example
1240 /// if it is infinity or NaN this function will panic.
1241pub fn f32_unsuffixed(f: f32) -> Literal {
1242if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1243Literal::_new(imp::Literal::f32_unsuffixed(f))
1244 }
12451246/// Creates a new suffixed floating-point literal.
1247 ///
1248 /// This constructor will create a literal like `1.0f32` where the value
1249 /// specified is the preceding part of the token and `f32` is the suffix of
1250 /// the token. This token will always be inferred to be an `f32` in the
1251 /// compiler. Literals created from negative numbers may not survive
1252 /// round-trips through `TokenStream` or strings and may be broken into two
1253 /// tokens (`-` and positive literal).
1254 ///
1255 /// # Panics
1256 ///
1257 /// This function requires that the specified float is finite, for example
1258 /// if it is infinity or NaN this function will panic.
1259pub fn f32_suffixed(f: f32) -> Literal {
1260if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1261Literal::_new(imp::Literal::f32_suffixed(f))
1262 }
12631264/// String literal.
1265pub fn string(string: &str) -> Literal {
1266Literal::_new(imp::Literal::string(string))
1267 }
12681269/// Character literal.
1270pub fn character(ch: char) -> Literal {
1271Literal::_new(imp::Literal::character(ch))
1272 }
12731274/// Byte character literal.
1275pub fn byte_character(byte: u8) -> Literal {
1276Literal::_new(imp::Literal::byte_character(byte))
1277 }
12781279/// Byte string literal.
1280pub fn byte_string(bytes: &[u8]) -> Literal {
1281Literal::_new(imp::Literal::byte_string(bytes))
1282 }
12831284/// C string literal.
1285pub fn c_string(string: &CStr) -> Literal {
1286Literal::_new(imp::Literal::c_string(string))
1287 }
12881289/// Returns the span encompassing this literal.
1290pub fn span(&self) -> Span {
1291Span::_new(self.inner.span())
1292 }
12931294/// Configures the span associated for this literal.
1295pub fn set_span(&mut self, span: Span) {
1296self.inner.set_span(span.inner);
1297 }
12981299/// Returns a `Span` that is a subset of `self.span()` containing only
1300 /// the source bytes in range `range`. Returns `None` if the would-be
1301 /// trimmed span is outside the bounds of `self`.
1302 ///
1303 /// Warning: the underlying [`proc_macro::Literal::subspan`] method is
1304 /// nightly-only. When called from within a procedural macro not using a
1305 /// nightly compiler, this method will always return `None`.
1306pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1307self.inner.subspan(range).map(Span::_new)
1308 }
13091310/// Returns the unescaped string value if this is a string literal.
1311#[cfg(procmacro2_semver_exempt)]
1312pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1313let repr = self.to_string();
13141315if repr.starts_with('"') && repr[1..].ends_with('"') {
1316let quoted = &repr[1..repr.len() - 1];
1317let mut value = String::with_capacity(quoted.len());
1318let mut error = None;
1319 rustc_literal_escaper::unescape_str(quoted, |_range, res| match res {
1320Ok(ch) => value.push(ch),
1321Err(err) => {
1322if err.is_fatal() {
1323error = Some(ConversionErrorKind::FailedToUnescape(err));
1324 }
1325 }
1326 });
1327return match error {
1328Some(error) => Err(error),
1329None => Ok(value),
1330 };
1331 }
13321333if repr.starts_with('r') {
1334if let Some(raw) = get_raw(&repr[1..]) {
1335return Ok(raw.to_owned());
1336 }
1337 }
13381339Err(ConversionErrorKind::InvalidLiteralKind)
1340 }
13411342/// Returns the unescaped string value (including nul terminator) if this is
1343 /// a c-string literal.
1344#[cfg(procmacro2_semver_exempt)]
1345pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1346let repr = self.to_string();
13471348if repr.starts_with("c\"") && repr[2..].ends_with('"') {
1349let quoted = &repr[2..repr.len() - 1];
1350let mut value = Vec::with_capacity(quoted.len());
1351let mut error = None;
1352 rustc_literal_escaper::unescape_c_str(quoted, |_range, res| match res {
1353Ok(MixedUnit::Char(ch)) => {
1354value.extend_from_slice(ch.get().encode_utf8(&mut [0; 4]).as_bytes());
1355 }
1356Ok(MixedUnit::HighByte(byte)) => value.push(byte.get()),
1357Err(err) => {
1358if err.is_fatal() {
1359error = Some(ConversionErrorKind::FailedToUnescape(err));
1360 }
1361 }
1362 });
1363return match error {
1364Some(error) => Err(error),
1365None => {
1366value.push(b'\0');
1367Ok(value)
1368 }
1369 };
1370 }
13711372if repr.starts_with("cr") {
1373if let Some(raw) = get_raw(&repr[2..]) {
1374let mut value = Vec::with_capacity(raw.len() + 1);
1375value.extend_from_slice(raw.as_bytes());
1376value.push(b'\0');
1377return Ok(value);
1378 }
1379 }
13801381Err(ConversionErrorKind::InvalidLiteralKind)
1382 }
13831384/// Returns the unescaped string value if this is a byte string literal.
1385#[cfg(procmacro2_semver_exempt)]
1386pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1387let repr = self.to_string();
13881389if repr.starts_with("b\"") && repr[2..].ends_with('"') {
1390let quoted = &repr[2..repr.len() - 1];
1391let mut value = Vec::with_capacity(quoted.len());
1392let mut error = None;
1393 rustc_literal_escaper::unescape_byte_str(quoted, |_range, res| match res {
1394Ok(byte) => value.push(byte),
1395Err(err) => {
1396if err.is_fatal() {
1397error = Some(ConversionErrorKind::FailedToUnescape(err));
1398 }
1399 }
1400 });
1401return match error {
1402Some(error) => Err(error),
1403None => Ok(value),
1404 };
1405 }
14061407if repr.starts_with("br") {
1408if let Some(raw) = get_raw(&repr[2..]) {
1409return Ok(raw.as_bytes().to_owned());
1410 }
1411 }
14121413Err(ConversionErrorKind::InvalidLiteralKind)
1414 }
14151416// Intended for the `quote!` macro to use when constructing a proc-macro2
1417 // token out of a macro_rules $:literal token, which is already known to be
1418 // a valid literal. This avoids reparsing/validating the literal's string
1419 // representation. This is not public API other than for quote.
1420#[doc(hidden)]
1421pub unsafe fn from_str_unchecked(repr: &str) -> Self {
1422Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })
1423 }
1424}
14251426impl FromStrfor Literal {
1427type Err = LexError;
14281429fn from_str(repr: &str) -> Result<Self, LexError> {
1430match imp::Literal::from_str_checked(repr) {
1431Ok(lit) => Ok(Literal::_new(lit)),
1432Err(lex) => Err(LexError {
1433 inner: lex,
1434 _marker: MARKER,
1435 }),
1436 }
1437 }
1438}
14391440impl Debugfor Literal {
1441fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1442 Debug::fmt(&self.inner, f)
1443 }
1444}
14451446impl Displayfor Literal {
1447fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1448 Display::fmt(&self.inner, f)
1449 }
1450}
14511452/// Error when retrieving a string literal's unescaped value.
1453#[cfg(procmacro2_semver_exempt)]
1454#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ConversionErrorKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ConversionErrorKind::FailedToUnescape(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FailedToUnescape", &__self_0),
ConversionErrorKind::InvalidLiteralKind =>
::core::fmt::Formatter::write_str(f, "InvalidLiteralKind"),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ConversionErrorKind {
#[inline]
fn eq(&self, other: &ConversionErrorKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ConversionErrorKind::FailedToUnescape(__self_0),
ConversionErrorKind::FailedToUnescape(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ConversionErrorKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) -> () {
let _: ::core::cmp::AssertParamIsEq<EscapeError>;
}
}Eq)]
1455pub enum ConversionErrorKind {
1456/// The literal is of the right string kind, but its contents are malformed
1457 /// in a way that cannot be unescaped to a value.
1458FailedToUnescape(EscapeError),
1459/// The literal is not of the string kind whose value was requested, for
1460 /// example byte string vs UTF-8 string.
1461InvalidLiteralKind,
1462}
14631464// ###"..."### -> ...
1465#[cfg(procmacro2_semver_exempt)]
1466fn get_raw(repr: &str) -> Option<&str> {
1467let pounds = repr.len() - repr.trim_start_matches('#').len();
1468if repr.len() >= pounds + 1 + 1 + pounds1469 && repr[pounds..].starts_with('"')
1470 && repr.trim_end_matches('#').len() + pounds == repr.len()
1471 && repr[..repr.len() - pounds].ends_with('"')
1472 {
1473Some(&repr[pounds + 1..repr.len() - pounds - 1])
1474 } else {
1475None1476 }
1477}
14781479/// Public implementation details for the `TokenStream` type, such as iterators.
1480pub mod token_stream {
1481use crate::marker::{ProcMacroAutoTraits, MARKER};
1482use crate::{imp, TokenTree};
1483use core::fmt::{self, Debug};
14841485pub use crate::TokenStream;
14861487/// An iterator over `TokenStream`'s `TokenTree`s.
1488 ///
1489 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1490 /// delimited groups, and returns whole groups as token trees.
1491#[derive(#[automatically_derived]
impl ::core::clone::Clone for IntoIter {
#[inline]
fn clone(&self) -> IntoIter {
IntoIter {
inner: ::core::clone::Clone::clone(&self.inner),
_marker: ::core::clone::Clone::clone(&self._marker),
}
}
}Clone)]
1492pub struct IntoIter {
1493 inner: imp::TokenTreeIter,
1494 _marker: ProcMacroAutoTraits,
1495 }
14961497impl Iteratorfor IntoIter {
1498type Item = TokenTree;
14991500fn next(&mut self) -> Option<TokenTree> {
1501self.inner.next()
1502 }
15031504fn size_hint(&self) -> (usize, Option<usize>) {
1505self.inner.size_hint()
1506 }
1507 }
15081509impl Debugfor IntoIter {
1510fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1511f.write_str("TokenStream ")?;
1512f.debug_list().entries(self.clone()).finish()
1513 }
1514 }
15151516impl IntoIteratorfor TokenStream {
1517type Item = TokenTree;
1518type IntoIter = IntoIter;
15191520fn into_iter(self) -> IntoIter {
1521IntoIter {
1522 inner: self.inner.into_iter(),
1523 _marker: MARKER,
1524 }
1525 }
1526 }
1527}