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// Proc-macro2 types in rustdoc of other crates get linked to here.
87#![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.104")]
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;
139140#[cfg(feature = "proc-macro")]
141extern crate proc_macro;
142143mod marker;
144mod parse;
145mod probe;
146mod rcvec;
147148#[cfg(wrap_proc_macro)]
149mod detection;
150151// Public for proc_macro2::fallback::force() and unforce(), but those are quite
152// a niche use case so we omit it from rustdoc.
153#[doc(hidden)]
154pub mod fallback;
155156pub mod extra;
157158#[cfg(not(wrap_proc_macro))]
159use crate::fallback as imp;
160#[path = "wrapper.rs"]
161#[cfg(wrap_proc_macro)]
162mod imp;
163164#[cfg(span_locations)]
165mod location;
166167#[cfg(procmacro2_semver_exempt)]
168mod num;
169#[cfg(procmacro2_semver_exempt)]
170#[allow(dead_code)]
171mod rustc_literal_escaper;
172173use crate::extra::DelimSpan;
174use crate::marker::{ProcMacroAutoTraits, MARKER};
175#[cfg(procmacro2_semver_exempt)]
176use crate::rustc_literal_escaper::MixedUnit;
177use core::cmp::Ordering;
178use core::fmt::{self, Debug, Display};
179use core::hash::{Hash, Hasher};
180#[cfg(span_locations)]
181use core::ops::Range;
182use core::ops::RangeBounds;
183use core::str::FromStr;
184use std::error::Error;
185use std::ffi::CStr;
186#[cfg(span_locations)]
187use std::path::PathBuf;
188189#[cfg(span_locations)]
190#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
191pub use crate::location::LineColumn;
192193#[cfg(procmacro2_semver_exempt)]
194#[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
195pub use crate::rustc_literal_escaper::EscapeError;
196197/// An abstract stream of tokens, or more concretely a sequence of token trees.
198///
199/// This type provides interfaces for iterating over token trees and for
200/// collecting token trees into one stream.
201///
202/// Token stream is both the input and output of `#[proc_macro]`,
203/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
204#[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)]
205pub struct TokenStream {
206 inner: imp::TokenStream,
207 _marker: ProcMacroAutoTraits,
208}
209210/// Error returned from `TokenStream::from_str`.
211pub struct LexError {
212 inner: imp::LexError,
213 _marker: ProcMacroAutoTraits,
214}
215216impl TokenStream {
217fn _new(inner: imp::TokenStream) -> Self {
218TokenStream {
219inner,
220 _marker: MARKER,
221 }
222 }
223224fn _new_fallback(inner: fallback::TokenStream) -> Self {
225TokenStream {
226 inner: imp::TokenStream::from(inner),
227 _marker: MARKER,
228 }
229 }
230231/// Returns an empty `TokenStream` containing no token trees.
232pub fn new() -> Self {
233TokenStream::_new(imp::TokenStream::new())
234 }
235236/// Checks if this `TokenStream` is empty.
237pub fn is_empty(&self) -> bool {
238self.inner.is_empty()
239 }
240}
241242/// `TokenStream::default()` returns an empty stream,
243/// i.e. this is equivalent with `TokenStream::new()`.
244impl Defaultfor TokenStream {
245fn default() -> Self {
246TokenStream::new()
247 }
248}
249250/// Attempts to break the string into tokens and parse those tokens into a token
251/// stream.
252///
253/// May fail for a number of reasons, for example, if the string contains
254/// unbalanced delimiters or characters not existing in the language.
255///
256/// NOTE: Some errors may cause panics instead of returning `LexError`. We
257/// reserve the right to change these errors into `LexError`s later.
258impl FromStrfor TokenStream {
259type Err = LexError;
260261fn from_str(src: &str) -> Result<TokenStream, LexError> {
262match imp::TokenStream::from_str_checked(src) {
263Ok(tokens) => Ok(TokenStream::_new(tokens)),
264Err(lex) => Err(LexError {
265 inner: lex,
266 _marker: MARKER,
267 }),
268 }
269 }
270}
271272#[cfg(feature = "proc-macro")]
273#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
274impl From<proc_macro::TokenStream> for TokenStream {
275fn from(inner: proc_macro::TokenStream) -> Self {
276TokenStream::_new(imp::TokenStream::from(inner))
277 }
278}
279280#[cfg(feature = "proc-macro")]
281#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
282impl From<TokenStream> for proc_macro::TokenStream {
283fn from(inner: TokenStream) -> Self {
284 proc_macro::TokenStream::from(inner.inner)
285 }
286}
287288impl From<TokenTree> for TokenStream {
289fn from(token: TokenTree) -> Self {
290TokenStream::_new(imp::TokenStream::from(token))
291 }
292}
293294impl Extend<TokenTree> for TokenStream {
295fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, tokens: I) {
296self.inner.extend(tokens);
297 }
298}
299300impl Extend<TokenStream> for TokenStream {
301fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
302self.inner
303 .extend(streams.into_iter().map(|stream| stream.inner));
304 }
305}
306307impl Extend<Group> for TokenStream {
308fn extend<I: IntoIterator<Item = Group>>(&mut self, tokens: I) {
309self.inner.extend(tokens.into_iter().map(TokenTree::Group));
310 }
311}
312313impl Extend<Ident> for TokenStream {
314fn extend<I: IntoIterator<Item = Ident>>(&mut self, tokens: I) {
315self.inner.extend(tokens.into_iter().map(TokenTree::Ident));
316 }
317}
318319impl Extend<Punct> for TokenStream {
320fn extend<I: IntoIterator<Item = Punct>>(&mut self, tokens: I) {
321self.inner.extend(tokens.into_iter().map(TokenTree::Punct));
322 }
323}
324325impl Extend<Literal> for TokenStream {
326fn extend<I: IntoIterator<Item = Literal>>(&mut self, tokens: I) {
327self.inner
328 .extend(tokens.into_iter().map(TokenTree::Literal));
329 }
330}
331332/// Collects a number of token trees into a single stream.
333impl FromIterator<TokenTree> for TokenStream {
334fn from_iter<I: IntoIterator<Item = TokenTree>>(tokens: I) -> Self {
335TokenStream::_new(tokens.into_iter().collect())
336 }
337}
338339impl FromIterator<TokenStream> for TokenStream {
340fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
341TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
342 }
343}
344345/// Prints the token stream as a string that is supposed to be losslessly
346/// convertible back into the same token stream (modulo spans), except for
347/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
348/// numeric literals.
349impl Displayfor TokenStream {
350fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
351 Display::fmt(&self.inner, f)
352 }
353}
354355/// Prints token in a form convenient for debugging.
356impl Debugfor TokenStream {
357fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
358 Debug::fmt(&self.inner, f)
359 }
360}
361362impl LexError {
363pub fn span(&self) -> Span {
364Span::_new(self.inner.span())
365 }
366}
367368impl Debugfor LexError {
369fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
370 Debug::fmt(&self.inner, f)
371 }
372}
373374impl Displayfor LexError {
375fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
376 Display::fmt(&self.inner, f)
377 }
378}
379380impl Errorfor LexError {}
381382/// A region of source code, along with macro expansion information.
383#[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)]
384pub struct Span {
385 inner: imp::Span,
386 _marker: ProcMacroAutoTraits,
387}
388389impl Span {
390fn _new(inner: imp::Span) -> Self {
391Span {
392inner,
393 _marker: MARKER,
394 }
395 }
396397fn _new_fallback(inner: fallback::Span) -> Self {
398Span {
399 inner: imp::Span::from(inner),
400 _marker: MARKER,
401 }
402 }
403404/// The span of the invocation of the current procedural macro.
405 ///
406 /// Identifiers created with this span will be resolved as if they were
407 /// written directly at the macro call location (call-site hygiene) and
408 /// other code at the macro call site will be able to refer to them as well.
409pub fn call_site() -> Self {
410Span::_new(imp::Span::call_site())
411 }
412413/// The span located at the invocation of the procedural macro, but with
414 /// local variables, labels, and `$crate` resolved at the definition site
415 /// of the macro. This is the same hygiene behavior as `macro_rules`.
416pub fn mixed_site() -> Self {
417Span::_new(imp::Span::mixed_site())
418 }
419420/// A span that resolves at the macro definition site.
421 ///
422 /// This method is semver exempt and not exposed by default.
423#[cfg(procmacro2_semver_exempt)]
424 #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
425pub fn def_site() -> Self {
426Span::_new(imp::Span::def_site())
427 }
428429/// Creates a new span with the same line/column information as `self` but
430 /// that resolves symbols as though it were at `other`.
431pub fn resolved_at(&self, other: Span) -> Span {
432Span::_new(self.inner.resolved_at(other.inner))
433 }
434435/// Creates a new span with the same name resolution behavior as `self` but
436 /// with the line/column information of `other`.
437pub fn located_at(&self, other: Span) -> Span {
438Span::_new(self.inner.located_at(other.inner))
439 }
440441/// Convert `proc_macro2::Span` to `proc_macro::Span`.
442 ///
443 /// This method is available when building with a nightly compiler, or when
444 /// building with rustc 1.29+ *without* semver exempt features.
445 ///
446 /// # Panics
447 ///
448 /// Panics if called from outside of a procedural macro. Unlike
449 /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
450 /// the context of a procedural macro invocation.
451#[cfg(wrap_proc_macro)]
452pub fn unwrap(self) -> proc_macro::Span {
453self.inner.unwrap()
454 }
455456// Soft deprecated. Please use Span::unwrap.
457#[cfg(wrap_proc_macro)]
458 #[doc(hidden)]
459pub fn unstable(self) -> proc_macro::Span {
460self.unwrap()
461 }
462463/// Returns the span's byte position range in the source file.
464 ///
465 /// This method requires the `"span-locations"` feature to be enabled.
466 ///
467 /// When executing in a procedural macro context, the returned range is only
468 /// accurate if compiled with a nightly toolchain. The stable toolchain does
469 /// not have this information available. When executing outside of a
470 /// procedural macro, such as main.rs or build.rs, the byte range is always
471 /// accurate regardless of toolchain.
472#[cfg(span_locations)]
473 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
474pub fn byte_range(&self) -> Range<usize> {
475self.inner.byte_range()
476 }
477478/// Get the starting line/column in the source file for this span.
479 ///
480 /// This method requires the `"span-locations"` feature to be enabled.
481 ///
482 /// When executing in a procedural macro context, the returned line/column
483 /// are only meaningful if compiled with a nightly toolchain. The stable
484 /// toolchain does not have this information available. When executing
485 /// outside of a procedural macro, such as main.rs or build.rs, the
486 /// line/column are always meaningful regardless of toolchain.
487#[cfg(span_locations)]
488 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
489pub fn start(&self) -> LineColumn {
490self.inner.start()
491 }
492493/// Get the ending line/column in the source file for this span.
494 ///
495 /// This method requires the `"span-locations"` feature to be enabled.
496 ///
497 /// When executing in a procedural macro context, the returned line/column
498 /// are only meaningful if compiled with a nightly toolchain. The stable
499 /// toolchain does not have this information available. When executing
500 /// outside of a procedural macro, such as main.rs or build.rs, the
501 /// line/column are always meaningful regardless of toolchain.
502#[cfg(span_locations)]
503 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
504pub fn end(&self) -> LineColumn {
505self.inner.end()
506 }
507508/// The path to the source file in which this span occurs, for display
509 /// purposes.
510 ///
511 /// This might not correspond to a valid file system path. It might be
512 /// remapped, or might be an artificial path such as `"<macro expansion>"`.
513#[cfg(span_locations)]
514 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
515pub fn file(&self) -> String {
516self.inner.file()
517 }
518519/// The path to the source file in which this span occurs on disk.
520 ///
521 /// This is the actual path on disk. It is unaffected by path remapping.
522 ///
523 /// This path should not be embedded in the output of the macro; prefer
524 /// `file()` instead.
525#[cfg(span_locations)]
526 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
527pub fn local_file(&self) -> Option<PathBuf> {
528self.inner.local_file()
529 }
530531/// Create a new span encompassing `self` and `other`.
532 ///
533 /// Returns `None` if `self` and `other` are from different files.
534 ///
535 /// Warning: the underlying [`proc_macro::Span::join`] method is
536 /// nightly-only. When called from within a procedural macro not using a
537 /// nightly compiler, this method will always return `None`.
538pub fn join(&self, other: Span) -> Option<Span> {
539self.inner.join(other.inner).map(Span::_new)
540 }
541542/// Compares two spans to see if they're equal.
543 ///
544 /// This method is semver exempt and not exposed by default.
545#[cfg(procmacro2_semver_exempt)]
546 #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
547pub fn eq(&self, other: &Span) -> bool {
548self.inner.eq(&other.inner)
549 }
550551/// Returns the source text behind a span. This preserves the original
552 /// source code, including spaces and comments. It only returns a result if
553 /// the span corresponds to real source code.
554 ///
555 /// Note: The observable result of a macro should only rely on the tokens
556 /// and not on this source text. The result of this function is a best
557 /// effort to be used for diagnostics only.
558pub fn source_text(&self) -> Option<String> {
559self.inner.source_text()
560 }
561}
562563/// Prints a span in a form convenient for debugging.
564impl Debugfor Span {
565fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
566 Debug::fmt(&self.inner, f)
567 }
568}
569570/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
571#[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)]
572pub enum TokenTree {
573/// A token stream surrounded by bracket delimiters.
574Group(Group),
575/// An identifier.
576Ident(Ident),
577/// A single punctuation character (`+`, `,`, `$`, etc.).
578Punct(Punct),
579/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
580Literal(Literal),
581}
582583impl TokenTree {
584/// Returns the span of this tree, delegating to the `span` method of
585 /// the contained token or a delimited stream.
586pub fn span(&self) -> Span {
587match self {
588 TokenTree::Group(t) => t.span(),
589 TokenTree::Ident(t) => t.span(),
590 TokenTree::Punct(t) => t.span(),
591 TokenTree::Literal(t) => t.span(),
592 }
593 }
594595/// Configures the span for *only this token*.
596 ///
597 /// Note that if this token is a `Group` then this method will not configure
598 /// the span of each of the internal tokens, this will simply delegate to
599 /// the `set_span` method of each variant.
600pub fn set_span(&mut self, span: Span) {
601match self {
602 TokenTree::Group(t) => t.set_span(span),
603 TokenTree::Ident(t) => t.set_span(span),
604 TokenTree::Punct(t) => t.set_span(span),
605 TokenTree::Literal(t) => t.set_span(span),
606 }
607 }
608}
609610impl From<Group> for TokenTree {
611fn from(g: Group) -> Self {
612 TokenTree::Group(g)
613 }
614}
615616impl From<Ident> for TokenTree {
617fn from(g: Ident) -> Self {
618 TokenTree::Ident(g)
619 }
620}
621622impl From<Punct> for TokenTree {
623fn from(g: Punct) -> Self {
624 TokenTree::Punct(g)
625 }
626}
627628impl From<Literal> for TokenTree {
629fn from(g: Literal) -> Self {
630 TokenTree::Literal(g)
631 }
632}
633634/// Prints the token tree as a string that is supposed to be losslessly
635/// convertible back into the same token tree (modulo spans), except for
636/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
637/// numeric literals.
638impl Displayfor TokenTree {
639fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
640match self {
641 TokenTree::Group(t) => Display::fmt(t, f),
642 TokenTree::Ident(t) => Display::fmt(t, f),
643 TokenTree::Punct(t) => Display::fmt(t, f),
644 TokenTree::Literal(t) => Display::fmt(t, f),
645 }
646 }
647}
648649/// Prints token tree in a form convenient for debugging.
650impl Debugfor TokenTree {
651fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
652// Each of these has the name in the struct type in the derived debug,
653 // so don't bother with an extra layer of indirection
654match self {
655 TokenTree::Group(t) => Debug::fmt(t, f),
656 TokenTree::Ident(t) => {
657let mut debug = f.debug_struct("Ident");
658debug.field("sym", &format_args!("{0}", t)format_args!("{}", t));
659 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
660debug.finish()
661 }
662 TokenTree::Punct(t) => Debug::fmt(t, f),
663 TokenTree::Literal(t) => Debug::fmt(t, f),
664 }
665 }
666}
667668/// A delimited token stream.
669///
670/// A `Group` internally contains a `TokenStream` which is surrounded by
671/// `Delimiter`s.
672#[derive(#[automatically_derived]
impl ::core::clone::Clone for Group {
#[inline]
fn clone(&self) -> Group {
Group { inner: ::core::clone::Clone::clone(&self.inner) }
}
}Clone)]
673pub struct Group {
674 inner: imp::Group,
675}
676677/// Describes how a sequence of token trees is delimited.
678#[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)]
679pub enum Delimiter {
680/// `( ... )`
681Parenthesis,
682/// `{ ... }`
683Brace,
684/// `[ ... ]`
685Bracket,
686/// `∅ ... ∅`
687 ///
688 /// An invisible delimiter, that may, for example, appear around tokens
689 /// coming from a "macro variable" `$var`. It is important to preserve
690 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
691 /// Invisible delimiters may not survive roundtrip of a token stream through
692 /// a string.
693 ///
694 /// <div class="warning">
695 ///
696 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
697 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
698 /// of a proc_macro macro are preserved, and only in very specific circumstances.
699 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
700 /// operator priorities as indicated above. The other `Delimiter` variants should be used
701 /// instead in this context. This is a rustc bug. For details, see
702 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
703 ///
704 /// </div>
705None,
706}
707708impl Group {
709fn _new(inner: imp::Group) -> Self {
710Group { inner }
711 }
712713fn _new_fallback(inner: fallback::Group) -> Self {
714Group {
715 inner: imp::Group::from(inner),
716 }
717 }
718719/// Creates a new `Group` with the given delimiter and token stream.
720 ///
721 /// This constructor will set the span for this group to
722 /// `Span::call_site()`. To change the span you can use the `set_span`
723 /// method below.
724pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
725Group {
726 inner: imp::Group::new(delimiter, stream.inner),
727 }
728 }
729730/// Returns the punctuation used as the delimiter for this group: a set of
731 /// parentheses, square brackets, or curly braces.
732pub fn delimiter(&self) -> Delimiter {
733self.inner.delimiter()
734 }
735736/// Returns the `TokenStream` of tokens that are delimited in this `Group`.
737 ///
738 /// Note that the returned token stream does not include the delimiter
739 /// returned above.
740pub fn stream(&self) -> TokenStream {
741TokenStream::_new(self.inner.stream())
742 }
743744/// Returns the span for the delimiters of this token stream, spanning the
745 /// entire `Group`.
746 ///
747 /// ```text
748 /// pub fn span(&self) -> Span {
749 /// ^^^^^^^
750 /// ```
751pub fn span(&self) -> Span {
752Span::_new(self.inner.span())
753 }
754755/// Returns the span pointing to the opening delimiter of this group.
756 ///
757 /// ```text
758 /// pub fn span_open(&self) -> Span {
759 /// ^
760 /// ```
761pub fn span_open(&self) -> Span {
762Span::_new(self.inner.span_open())
763 }
764765/// Returns the span pointing to the closing delimiter of this group.
766 ///
767 /// ```text
768 /// pub fn span_close(&self) -> Span {
769 /// ^
770 /// ```
771pub fn span_close(&self) -> Span {
772Span::_new(self.inner.span_close())
773 }
774775/// Returns an object that holds this group's `span_open()` and
776 /// `span_close()` together (in a more compact representation than holding
777 /// those 2 spans individually).
778pub fn delim_span(&self) -> DelimSpan {
779DelimSpan::new(&self.inner)
780 }
781782/// Configures the span for this `Group`'s delimiters, but not its internal
783 /// tokens.
784 ///
785 /// This method will **not** set the span of all the internal tokens spanned
786 /// by this group, but rather it will only set the span of the delimiter
787 /// tokens at the level of the `Group`.
788pub fn set_span(&mut self, span: Span) {
789self.inner.set_span(span.inner);
790 }
791}
792793/// Prints the group as a string that should be losslessly convertible back
794/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
795/// with `Delimiter::None` delimiters.
796impl Displayfor Group {
797fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
798 Display::fmt(&self.inner, formatter)
799 }
800}
801802impl Debugfor Group {
803fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
804 Debug::fmt(&self.inner, formatter)
805 }
806}
807808/// A `Punct` is a single punctuation character like `+`, `-` or `#`.
809///
810/// Multicharacter operators like `+=` are represented as two instances of
811/// `Punct` with different forms of `Spacing` returned.
812#[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)]
813pub struct Punct {
814 ch: char,
815 spacing: Spacing,
816 span: Span,
817}
818819/// Whether a `Punct` is followed immediately by another `Punct` or followed by
820/// another token or whitespace.
821#[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)]
822pub enum Spacing {
823/// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
824Alone,
825/// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.
826 ///
827 /// Additionally, single quote `'` can join with identifiers to form
828 /// lifetimes `'ident`.
829Joint,
830}
831832impl Punct {
833/// Creates a new `Punct` from the given character and spacing.
834 ///
835 /// The `ch` argument must be a valid punctuation character permitted by the
836 /// language, otherwise the function will panic.
837 ///
838 /// The returned `Punct` will have the default span of `Span::call_site()`
839 /// which can be further configured with the `set_span` method below.
840pub fn new(ch: char, spacing: Spacing) -> Self {
841if let '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';'
842| '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch843 {
844Punct {
845ch,
846spacing,
847 span: Span::call_site(),
848 }
849 } else {
850{
::core::panicking::panic_fmt(format_args!("unsupported proc macro punctuation character {0:?}",
ch));
};panic!("unsupported proc macro punctuation character {:?}", ch);
851 }
852 }
853854/// Returns the value of this punctuation character as `char`.
855pub fn as_char(&self) -> char {
856self.ch
857 }
858859/// Returns the spacing of this punctuation character, indicating whether
860 /// it's immediately followed by another `Punct` in the token stream, so
861 /// they can potentially be combined into a multicharacter operator
862 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
863 /// so the operator has certainly ended.
864pub fn spacing(&self) -> Spacing {
865self.spacing
866 }
867868/// Returns the span for this punctuation character.
869pub fn span(&self) -> Span {
870self.span
871 }
872873/// Configure the span for this punctuation character.
874pub fn set_span(&mut self, span: Span) {
875self.span = span;
876 }
877}
878879/// Prints the punctuation character as a string that should be losslessly
880/// convertible back into the same character.
881impl Displayfor Punct {
882fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
883 Display::fmt(&self.ch, f)
884 }
885}
886887impl Debugfor Punct {
888fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
889let mut debug = fmt.debug_struct("Punct");
890debug.field("char", &self.ch);
891debug.field("spacing", &self.spacing);
892 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
893debug.finish()
894 }
895}
896897/// A word of Rust code, which may be a keyword or legal variable name.
898///
899/// An identifier consists of at least one Unicode code point, the first of
900/// which has the XID_Start property and the rest of which have the XID_Continue
901/// property.
902///
903/// - The empty string is not an identifier. Use `Option<Ident>`.
904/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
905///
906/// An identifier constructed with `Ident::new` is permitted to be a Rust
907/// keyword, though parsing one through its [`Parse`] implementation rejects
908/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
909/// behaviour of `Ident::new`.
910///
911/// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html
912///
913/// # Examples
914///
915/// A new ident can be created from a string using the `Ident::new` function.
916/// A span must be provided explicitly which governs the name resolution
917/// behavior of the resulting identifier.
918///
919/// ```
920/// use proc_macro2::{Ident, Span};
921///
922/// fn main() {
923/// let call_ident = Ident::new("calligraphy", Span::call_site());
924///
925/// println!("{}", call_ident);
926/// }
927/// ```
928///
929/// An ident can be interpolated into a token stream using the `quote!` macro.
930///
931/// ```
932/// use proc_macro2::{Ident, Span};
933/// use quote::quote;
934///
935/// fn main() {
936/// let ident = Ident::new("demo", Span::call_site());
937///
938/// // Create a variable binding whose name is this ident.
939/// let expanded = quote! { let #ident = 10; };
940///
941/// // Create a variable binding with a slightly different name.
942/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
943/// let expanded = quote! { let #temp_ident = 10; };
944/// }
945/// ```
946///
947/// A string representation of the ident is available through the `to_string()`
948/// method.
949///
950/// ```
951/// # use proc_macro2::{Ident, Span};
952/// #
953/// # let ident = Ident::new("another_identifier", Span::call_site());
954/// #
955/// // Examine the ident as a string.
956/// let ident_string = ident.to_string();
957/// if ident_string.len() > 60 {
958/// println!("Very long identifier: {}", ident_string)
959/// }
960/// ```
961#[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)]
962pub struct Ident {
963 inner: imp::Ident,
964 _marker: ProcMacroAutoTraits,
965}
966967impl Ident {
968fn _new(inner: imp::Ident) -> Self {
969Ident {
970inner,
971 _marker: MARKER,
972 }
973 }
974975fn _new_fallback(inner: fallback::Ident) -> Self {
976Ident {
977 inner: imp::Ident::from(inner),
978 _marker: MARKER,
979 }
980 }
981982/// Creates a new `Ident` with the given `string` as well as the specified
983 /// `span`.
984 ///
985 /// The `string` argument must be a valid identifier permitted by the
986 /// language, otherwise the function will panic.
987 ///
988 /// Note that `span`, currently in rustc, configures the hygiene information
989 /// for this identifier.
990 ///
991 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
992 /// hygiene meaning that identifiers created with this span will be resolved
993 /// as if they were written directly at the location of the macro call, and
994 /// other code at the macro call site will be able to refer to them as well.
995 ///
996 /// Later spans like `Span::def_site()` will allow to opt-in to
997 /// "definition-site" hygiene meaning that identifiers created with this
998 /// span will be resolved at the location of the macro definition and other
999 /// code at the macro call site will not be able to refer to them.
1000 ///
1001 /// Due to the current importance of hygiene this constructor, unlike other
1002 /// tokens, requires a `Span` to be specified at construction.
1003 ///
1004 /// # Panics
1005 ///
1006 /// Panics if the input string is neither a keyword nor a legal variable
1007 /// name. If you are not sure whether the string contains an identifier and
1008 /// need to handle an error case, use
1009 /// <a href="https://docs.rs/syn/2.0/syn/fn.parse_str.html"><code
1010 /// style="padding-right:0;">syn::parse_str</code></a><code
1011 /// style="padding-left:0;">::<Ident></code>
1012 /// rather than `Ident::new`.
1013#[track_caller]
1014pub fn new(string: &str, span: Span) -> Self {
1015Ident::_new(imp::Ident::new_checked(string, span.inner))
1016 }
10171018/// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The
1019 /// `string` argument must be a valid identifier permitted by the language
1020 /// (including keywords, e.g. `fn`). Keywords which are usable in path
1021 /// segments (e.g. `self`, `super`) are not supported, and will cause a
1022 /// panic.
1023#[track_caller]
1024pub fn new_raw(string: &str, span: Span) -> Self {
1025Ident::_new(imp::Ident::new_raw_checked(string, span.inner))
1026 }
10271028/// Returns the span of this `Ident`.
1029pub fn span(&self) -> Span {
1030Span::_new(self.inner.span())
1031 }
10321033/// Configures the span of this `Ident`, possibly changing its hygiene
1034 /// context.
1035pub fn set_span(&mut self, span: Span) {
1036self.inner.set_span(span.inner);
1037 }
1038}
10391040impl PartialEqfor Ident {
1041fn eq(&self, other: &Ident) -> bool {
1042self.inner == other.inner
1043 }
1044}
10451046impl<T> PartialEq<T> for Ident1047where
1048T: ?Sized + AsRef<str>,
1049{
1050fn eq(&self, other: &T) -> bool {
1051self.inner == other1052 }
1053}
10541055impl Eqfor Ident {}
10561057impl PartialOrdfor Ident {
1058fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
1059Some(self.cmp(other))
1060 }
1061}
10621063impl Ordfor Ident {
1064fn cmp(&self, other: &Ident) -> Ordering {
1065self.to_string().cmp(&other.to_string())
1066 }
1067}
10681069impl Hashfor Ident {
1070fn hash<H: Hasher>(&self, hasher: &mut H) {
1071self.to_string().hash(hasher);
1072 }
1073}
10741075/// Prints the identifier as a string that should be losslessly convertible back
1076/// into the same identifier.
1077impl Displayfor Ident {
1078fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1079 Display::fmt(&self.inner, f)
1080 }
1081}
10821083impl Debugfor Ident {
1084fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1085 Debug::fmt(&self.inner, f)
1086 }
1087}
10881089/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
1090/// byte character (`b'a'`), an integer or floating point number with or without
1091/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1092///
1093/// Boolean literals like `true` and `false` do not belong here, they are
1094/// `Ident`s.
1095#[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)]
1096pub struct Literal {
1097 inner: imp::Literal,
1098 _marker: ProcMacroAutoTraits,
1099}
11001101macro_rules! suffixed_int_literals {
1102 ($($name:ident => $kind:ident,)*) => ($(
1103/// Creates a new suffixed integer literal with the specified value.
1104 ///
1105 /// This function will create an integer like `1u32` where the integer
1106 /// value specified is the first part of the token and the integral is
1107 /// also suffixed at the end. Literals created from negative numbers may
1108 /// not survive roundtrips through `TokenStream` or strings and may be
1109 /// broken into two tokens (`-` and positive literal).
1110 ///
1111 /// Literals created through this method have the `Span::call_site()`
1112 /// span by default, which can be configured with the `set_span` method
1113 /// below.
1114pub fn $name(n: $kind) -> Literal {
1115 Literal::_new(imp::Literal::$name(n))
1116 }
1117 )*)
1118}
11191120macro_rules! unsuffixed_int_literals {
1121 ($($name:ident => $kind:ident,)*) => ($(
1122/// Creates a new unsuffixed integer literal with the specified value.
1123 ///
1124 /// This function will create an integer like `1` where the integer
1125 /// value specified is the first part of the token. No suffix is
1126 /// specified on this token, meaning that invocations like
1127 /// `Literal::i8_unsuffixed(1)` are equivalent to
1128 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
1129 /// may not survive roundtrips through `TokenStream` or strings and may
1130 /// be broken into two tokens (`-` and positive literal).
1131 ///
1132 /// Literals created through this method have the `Span::call_site()`
1133 /// span by default, which can be configured with the `set_span` method
1134 /// below.
1135pub fn $name(n: $kind) -> Literal {
1136 Literal::_new(imp::Literal::$name(n))
1137 }
1138 )*)
1139}
11401141impl Literal {
1142fn _new(inner: imp::Literal) -> Self {
1143Literal {
1144inner,
1145 _marker: MARKER,
1146 }
1147 }
11481149fn _new_fallback(inner: fallback::Literal) -> Self {
1150Literal {
1151 inner: imp::Literal::from(inner),
1152 _marker: MARKER,
1153 }
1154 }
11551156n
Literal
Literal::_new(imp::Literal::isize_suffixed(n));suffixed_int_literals! {
1157 u8_suffixed => u8,
1158 u16_suffixed => u16,
1159 u32_suffixed => u32,
1160 u64_suffixed => u64,
1161 u128_suffixed => u128,
1162 usize_suffixed => usize,
1163 i8_suffixed => i8,
1164 i16_suffixed => i16,
1165 i32_suffixed => i32,
1166 i64_suffixed => i64,
1167 i128_suffixed => i128,
1168 isize_suffixed => isize,
1169 }11701171n
Literal
Literal::_new(imp::Literal::isize_unsuffixed(n));unsuffixed_int_literals! {
1172 u8_unsuffixed => u8,
1173 u16_unsuffixed => u16,
1174 u32_unsuffixed => u32,
1175 u64_unsuffixed => u64,
1176 u128_unsuffixed => u128,
1177 usize_unsuffixed => usize,
1178 i8_unsuffixed => i8,
1179 i16_unsuffixed => i16,
1180 i32_unsuffixed => i32,
1181 i64_unsuffixed => i64,
1182 i128_unsuffixed => i128,
1183 isize_unsuffixed => isize,
1184 }11851186/// Creates a new unsuffixed floating-point literal.
1187 ///
1188 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1189 /// the float's value is emitted directly into the token but no suffix is
1190 /// used, so it may be inferred to be a `f64` later in the compiler.
1191 /// Literals created from negative numbers may not survive round-trips
1192 /// through `TokenStream` or strings and may be broken into two tokens (`-`
1193 /// and positive literal).
1194 ///
1195 /// # Panics
1196 ///
1197 /// This function requires that the specified float is finite, for example
1198 /// if it is infinity or NaN this function will panic.
1199pub fn f64_unsuffixed(f: f64) -> Literal {
1200if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1201Literal::_new(imp::Literal::f64_unsuffixed(f))
1202 }
12031204/// Creates a new suffixed floating-point literal.
1205 ///
1206 /// This constructor will create a literal like `1.0f64` where the value
1207 /// specified is the preceding part of the token and `f64` is the suffix of
1208 /// the token. This token will always be inferred to be an `f64` in the
1209 /// compiler. Literals created from negative numbers may not survive
1210 /// round-trips through `TokenStream` or strings and may be broken into two
1211 /// tokens (`-` and positive literal).
1212 ///
1213 /// # Panics
1214 ///
1215 /// This function requires that the specified float is finite, for example
1216 /// if it is infinity or NaN this function will panic.
1217pub fn f64_suffixed(f: f64) -> Literal {
1218if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1219Literal::_new(imp::Literal::f64_suffixed(f))
1220 }
12211222/// Creates a new unsuffixed floating-point literal.
1223 ///
1224 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1225 /// the float's value is emitted directly into the token but no suffix is
1226 /// used, so it may be inferred to be a `f64` later in the compiler.
1227 /// Literals created from negative numbers may not survive round-trips
1228 /// through `TokenStream` or strings and may be broken into two tokens (`-`
1229 /// and positive literal).
1230 ///
1231 /// # Panics
1232 ///
1233 /// This function requires that the specified float is finite, for example
1234 /// if it is infinity or NaN this function will panic.
1235pub fn f32_unsuffixed(f: f32) -> Literal {
1236if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1237Literal::_new(imp::Literal::f32_unsuffixed(f))
1238 }
12391240/// Creates a new suffixed floating-point literal.
1241 ///
1242 /// This constructor will create a literal like `1.0f32` where the value
1243 /// specified is the preceding part of the token and `f32` is the suffix of
1244 /// the token. This token will always be inferred to be an `f32` in the
1245 /// compiler. Literals created from negative numbers may not survive
1246 /// round-trips through `TokenStream` or strings and may be broken into two
1247 /// tokens (`-` and positive literal).
1248 ///
1249 /// # Panics
1250 ///
1251 /// This function requires that the specified float is finite, for example
1252 /// if it is infinity or NaN this function will panic.
1253pub fn f32_suffixed(f: f32) -> Literal {
1254if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1255Literal::_new(imp::Literal::f32_suffixed(f))
1256 }
12571258/// String literal.
1259pub fn string(string: &str) -> Literal {
1260Literal::_new(imp::Literal::string(string))
1261 }
12621263/// Character literal.
1264pub fn character(ch: char) -> Literal {
1265Literal::_new(imp::Literal::character(ch))
1266 }
12671268/// Byte character literal.
1269pub fn byte_character(byte: u8) -> Literal {
1270Literal::_new(imp::Literal::byte_character(byte))
1271 }
12721273/// Byte string literal.
1274pub fn byte_string(bytes: &[u8]) -> Literal {
1275Literal::_new(imp::Literal::byte_string(bytes))
1276 }
12771278/// C string literal.
1279pub fn c_string(string: &CStr) -> Literal {
1280Literal::_new(imp::Literal::c_string(string))
1281 }
12821283/// Returns the span encompassing this literal.
1284pub fn span(&self) -> Span {
1285Span::_new(self.inner.span())
1286 }
12871288/// Configures the span associated for this literal.
1289pub fn set_span(&mut self, span: Span) {
1290self.inner.set_span(span.inner);
1291 }
12921293/// Returns a `Span` that is a subset of `self.span()` containing only
1294 /// the source bytes in range `range`. Returns `None` if the would-be
1295 /// trimmed span is outside the bounds of `self`.
1296 ///
1297 /// Warning: the underlying [`proc_macro::Literal::subspan`] method is
1298 /// nightly-only. When called from within a procedural macro not using a
1299 /// nightly compiler, this method will always return `None`.
1300pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1301self.inner.subspan(range).map(Span::_new)
1302 }
13031304/// Returns the unescaped string value if this is a string literal.
1305#[cfg(procmacro2_semver_exempt)]
1306pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1307let repr = self.to_string();
13081309if repr.starts_with('"') && repr[1..].ends_with('"') {
1310let quoted = &repr[1..repr.len() - 1];
1311let mut value = String::with_capacity(quoted.len());
1312let mut error = None;
1313 rustc_literal_escaper::unescape_str(quoted, |_range, res| match res {
1314Ok(ch) => value.push(ch),
1315Err(err) => {
1316if err.is_fatal() {
1317error = Some(ConversionErrorKind::FailedToUnescape(err));
1318 }
1319 }
1320 });
1321return match error {
1322Some(error) => Err(error),
1323None => Ok(value),
1324 };
1325 }
13261327if repr.starts_with('r') {
1328if let Some(raw) = get_raw(&repr[1..]) {
1329return Ok(raw.to_owned());
1330 }
1331 }
13321333Err(ConversionErrorKind::InvalidLiteralKind)
1334 }
13351336/// Returns the unescaped string value (including nul terminator) if this is
1337 /// a c-string literal.
1338#[cfg(procmacro2_semver_exempt)]
1339pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1340let repr = self.to_string();
13411342if repr.starts_with("c\"") && repr[2..].ends_with('"') {
1343let quoted = &repr[2..repr.len() - 1];
1344let mut value = Vec::with_capacity(quoted.len());
1345let mut error = None;
1346 rustc_literal_escaper::unescape_c_str(quoted, |_range, res| match res {
1347Ok(MixedUnit::Char(ch)) => {
1348value.extend_from_slice(ch.get().encode_utf8(&mut [0; 4]).as_bytes());
1349 }
1350Ok(MixedUnit::HighByte(byte)) => value.push(byte.get()),
1351Err(err) => {
1352if err.is_fatal() {
1353error = Some(ConversionErrorKind::FailedToUnescape(err));
1354 }
1355 }
1356 });
1357return match error {
1358Some(error) => Err(error),
1359None => {
1360value.push(b'\0');
1361Ok(value)
1362 }
1363 };
1364 }
13651366if repr.starts_with("cr") {
1367if let Some(raw) = get_raw(&repr[2..]) {
1368let mut value = Vec::with_capacity(raw.len() + 1);
1369value.extend_from_slice(raw.as_bytes());
1370value.push(b'\0');
1371return Ok(value);
1372 }
1373 }
13741375Err(ConversionErrorKind::InvalidLiteralKind)
1376 }
13771378/// Returns the unescaped string value if this is a byte string literal.
1379#[cfg(procmacro2_semver_exempt)]
1380pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1381let repr = self.to_string();
13821383if repr.starts_with("b\"") && repr[2..].ends_with('"') {
1384let quoted = &repr[2..repr.len() - 1];
1385let mut value = Vec::with_capacity(quoted.len());
1386let mut error = None;
1387 rustc_literal_escaper::unescape_byte_str(quoted, |_range, res| match res {
1388Ok(byte) => value.push(byte),
1389Err(err) => {
1390if err.is_fatal() {
1391error = Some(ConversionErrorKind::FailedToUnescape(err));
1392 }
1393 }
1394 });
1395return match error {
1396Some(error) => Err(error),
1397None => Ok(value),
1398 };
1399 }
14001401if repr.starts_with("br") {
1402if let Some(raw) = get_raw(&repr[2..]) {
1403return Ok(raw.as_bytes().to_owned());
1404 }
1405 }
14061407Err(ConversionErrorKind::InvalidLiteralKind)
1408 }
14091410// Intended for the `quote!` macro to use when constructing a proc-macro2
1411 // token out of a macro_rules $:literal token, which is already known to be
1412 // a valid literal. This avoids reparsing/validating the literal's string
1413 // representation. This is not public API other than for quote.
1414#[doc(hidden)]
1415pub unsafe fn from_str_unchecked(repr: &str) -> Self {
1416Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })
1417 }
1418}
14191420impl FromStrfor Literal {
1421type Err = LexError;
14221423fn from_str(repr: &str) -> Result<Self, LexError> {
1424match imp::Literal::from_str_checked(repr) {
1425Ok(lit) => Ok(Literal::_new(lit)),
1426Err(lex) => Err(LexError {
1427 inner: lex,
1428 _marker: MARKER,
1429 }),
1430 }
1431 }
1432}
14331434impl Debugfor Literal {
1435fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1436 Debug::fmt(&self.inner, f)
1437 }
1438}
14391440impl Displayfor Literal {
1441fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1442 Display::fmt(&self.inner, f)
1443 }
1444}
14451446/// Error when retrieving a string literal's unescaped value.
1447#[cfg(procmacro2_semver_exempt)]
1448#[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)]
1449pub enum ConversionErrorKind {
1450/// The literal is of the right string kind, but its contents are malformed
1451 /// in a way that cannot be unescaped to a value.
1452FailedToUnescape(EscapeError),
1453/// The literal is not of the string kind whose value was requested, for
1454 /// example byte string vs UTF-8 string.
1455InvalidLiteralKind,
1456}
14571458// ###"..."### -> ...
1459#[cfg(procmacro2_semver_exempt)]
1460fn get_raw(repr: &str) -> Option<&str> {
1461let pounds = repr.len() - repr.trim_start_matches('#').len();
1462if repr.len() >= pounds + 1 + 1 + pounds1463 && repr[pounds..].starts_with('"')
1464 && repr.trim_end_matches('#').len() + pounds == repr.len()
1465 && repr[..repr.len() - pounds].ends_with('"')
1466 {
1467Some(&repr[pounds + 1..repr.len() - pounds - 1])
1468 } else {
1469None1470 }
1471}
14721473/// Public implementation details for the `TokenStream` type, such as iterators.
1474pub mod token_stream {
1475use crate::marker::{ProcMacroAutoTraits, MARKER};
1476use crate::{imp, TokenTree};
1477use core::fmt::{self, Debug};
14781479pub use crate::TokenStream;
14801481/// An iterator over `TokenStream`'s `TokenTree`s.
1482 ///
1483 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1484 /// delimited groups, and returns whole groups as token trees.
1485#[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)]
1486pub struct IntoIter {
1487 inner: imp::TokenTreeIter,
1488 _marker: ProcMacroAutoTraits,
1489 }
14901491impl Iteratorfor IntoIter {
1492type Item = TokenTree;
14931494fn next(&mut self) -> Option<TokenTree> {
1495self.inner.next()
1496 }
14971498fn size_hint(&self) -> (usize, Option<usize>) {
1499self.inner.size_hint()
1500 }
1501 }
15021503impl Debugfor IntoIter {
1504fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1505f.write_str("TokenStream ")?;
1506f.debug_list().entries(self.clone()).finish()
1507 }
1508 }
15091510impl IntoIteratorfor TokenStream {
1511type Item = TokenTree;
1512type IntoIter = IntoIter;
15131514fn into_iter(self) -> IntoIter {
1515IntoIter {
1516 inner: self.inner.into_iter(),
1517 _marker: MARKER,
1518 }
1519 }
1520 }
1521}