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.60.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.103")]
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, streams: I) {
296self.inner.extend(streams);
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}
306307/// Collects a number of token trees into a single stream.
308impl FromIterator<TokenTree> for TokenStream {
309fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
310TokenStream::_new(streams.into_iter().collect())
311 }
312}
313impl FromIterator<TokenStream> for TokenStream {
314fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
315TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
316 }
317}
318319/// Prints the token stream as a string that is supposed to be losslessly
320/// convertible back into the same token stream (modulo spans), except for
321/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
322/// numeric literals.
323impl Displayfor TokenStream {
324fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
325 Display::fmt(&self.inner, f)
326 }
327}
328329/// Prints token in a form convenient for debugging.
330impl Debugfor TokenStream {
331fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
332 Debug::fmt(&self.inner, f)
333 }
334}
335336impl LexError {
337pub fn span(&self) -> Span {
338Span::_new(self.inner.span())
339 }
340}
341342impl Debugfor LexError {
343fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
344 Debug::fmt(&self.inner, f)
345 }
346}
347348impl Displayfor LexError {
349fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
350 Display::fmt(&self.inner, f)
351 }
352}
353354impl Errorfor LexError {}
355356/// A region of source code, along with macro expansion information.
357#[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)]
358pub struct Span {
359 inner: imp::Span,
360 _marker: ProcMacroAutoTraits,
361}
362363impl Span {
364fn _new(inner: imp::Span) -> Self {
365Span {
366inner,
367 _marker: MARKER,
368 }
369 }
370371fn _new_fallback(inner: fallback::Span) -> Self {
372Span {
373 inner: imp::Span::from(inner),
374 _marker: MARKER,
375 }
376 }
377378/// The span of the invocation of the current procedural macro.
379 ///
380 /// Identifiers created with this span will be resolved as if they were
381 /// written directly at the macro call location (call-site hygiene) and
382 /// other code at the macro call site will be able to refer to them as well.
383pub fn call_site() -> Self {
384Span::_new(imp::Span::call_site())
385 }
386387/// The span located at the invocation of the procedural macro, but with
388 /// local variables, labels, and `$crate` resolved at the definition site
389 /// of the macro. This is the same hygiene behavior as `macro_rules`.
390pub fn mixed_site() -> Self {
391Span::_new(imp::Span::mixed_site())
392 }
393394/// A span that resolves at the macro definition site.
395 ///
396 /// This method is semver exempt and not exposed by default.
397#[cfg(procmacro2_semver_exempt)]
398 #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
399pub fn def_site() -> Self {
400 Span::_new(imp::Span::def_site())
401 }
402403/// Creates a new span with the same line/column information as `self` but
404 /// that resolves symbols as though it were at `other`.
405pub fn resolved_at(&self, other: Span) -> Span {
406Span::_new(self.inner.resolved_at(other.inner))
407 }
408409/// Creates a new span with the same name resolution behavior as `self` but
410 /// with the line/column information of `other`.
411pub fn located_at(&self, other: Span) -> Span {
412Span::_new(self.inner.located_at(other.inner))
413 }
414415/// Convert `proc_macro2::Span` to `proc_macro::Span`.
416 ///
417 /// This method is available when building with a nightly compiler, or when
418 /// building with rustc 1.29+ *without* semver exempt features.
419 ///
420 /// # Panics
421 ///
422 /// Panics if called from outside of a procedural macro. Unlike
423 /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
424 /// the context of a procedural macro invocation.
425#[cfg(wrap_proc_macro)]
426pub fn unwrap(self) -> proc_macro::Span {
427self.inner.unwrap()
428 }
429430// Soft deprecated. Please use Span::unwrap.
431#[cfg(wrap_proc_macro)]
432 #[doc(hidden)]
433pub fn unstable(self) -> proc_macro::Span {
434self.unwrap()
435 }
436437/// Returns the span's byte position range in the source file.
438 ///
439 /// This method requires the `"span-locations"` feature to be enabled.
440 ///
441 /// When executing in a procedural macro context, the returned range is only
442 /// accurate if compiled with a nightly toolchain. The stable toolchain does
443 /// not have this information available. When executing outside of a
444 /// procedural macro, such as main.rs or build.rs, the byte range is always
445 /// accurate regardless of toolchain.
446#[cfg(span_locations)]
447 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
448pub fn byte_range(&self) -> Range<usize> {
449self.inner.byte_range()
450 }
451452/// Get the starting line/column in the source file for this span.
453 ///
454 /// This method requires the `"span-locations"` feature to be enabled.
455 ///
456 /// When executing in a procedural macro context, the returned line/column
457 /// are only meaningful if compiled with a nightly toolchain. The stable
458 /// toolchain does not have this information available. When executing
459 /// outside of a procedural macro, such as main.rs or build.rs, the
460 /// line/column are always meaningful regardless of toolchain.
461#[cfg(span_locations)]
462 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
463pub fn start(&self) -> LineColumn {
464self.inner.start()
465 }
466467/// Get the ending line/column in the source file for this span.
468 ///
469 /// This method requires the `"span-locations"` feature to be enabled.
470 ///
471 /// When executing in a procedural macro context, the returned line/column
472 /// are only meaningful if compiled with a nightly toolchain. The stable
473 /// toolchain does not have this information available. When executing
474 /// outside of a procedural macro, such as main.rs or build.rs, the
475 /// line/column are always meaningful regardless of toolchain.
476#[cfg(span_locations)]
477 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
478pub fn end(&self) -> LineColumn {
479self.inner.end()
480 }
481482/// The path to the source file in which this span occurs, for display
483 /// purposes.
484 ///
485 /// This might not correspond to a valid file system path. It might be
486 /// remapped, or might be an artificial path such as `"<macro expansion>"`.
487#[cfg(span_locations)]
488 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
489pub fn file(&self) -> String {
490self.inner.file()
491 }
492493/// The path to the source file in which this span occurs on disk.
494 ///
495 /// This is the actual path on disk. It is unaffected by path remapping.
496 ///
497 /// This path should not be embedded in the output of the macro; prefer
498 /// `file()` instead.
499#[cfg(span_locations)]
500 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]
501pub fn local_file(&self) -> Option<PathBuf> {
502self.inner.local_file()
503 }
504505/// Create a new span encompassing `self` and `other`.
506 ///
507 /// Returns `None` if `self` and `other` are from different files.
508 ///
509 /// Warning: the underlying [`proc_macro::Span::join`] method is
510 /// nightly-only. When called from within a procedural macro not using a
511 /// nightly compiler, this method will always return `None`.
512pub fn join(&self, other: Span) -> Option<Span> {
513self.inner.join(other.inner).map(Span::_new)
514 }
515516/// Compares two spans to see if they're equal.
517 ///
518 /// This method is semver exempt and not exposed by default.
519#[cfg(procmacro2_semver_exempt)]
520 #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]
521pub fn eq(&self, other: &Span) -> bool {
522self.inner.eq(&other.inner)
523 }
524525/// Returns the source text behind a span. This preserves the original
526 /// source code, including spaces and comments. It only returns a result if
527 /// the span corresponds to real source code.
528 ///
529 /// Note: The observable result of a macro should only rely on the tokens
530 /// and not on this source text. The result of this function is a best
531 /// effort to be used for diagnostics only.
532pub fn source_text(&self) -> Option<String> {
533self.inner.source_text()
534 }
535}
536537/// Prints a span in a form convenient for debugging.
538impl Debugfor Span {
539fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
540 Debug::fmt(&self.inner, f)
541 }
542}
543544/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
545#[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)]
546pub enum TokenTree {
547/// A token stream surrounded by bracket delimiters.
548Group(Group),
549/// An identifier.
550Ident(Ident),
551/// A single punctuation character (`+`, `,`, `$`, etc.).
552Punct(Punct),
553/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
554Literal(Literal),
555}
556557impl TokenTree {
558/// Returns the span of this tree, delegating to the `span` method of
559 /// the contained token or a delimited stream.
560pub fn span(&self) -> Span {
561match self {
562 TokenTree::Group(t) => t.span(),
563 TokenTree::Ident(t) => t.span(),
564 TokenTree::Punct(t) => t.span(),
565 TokenTree::Literal(t) => t.span(),
566 }
567 }
568569/// Configures the span for *only this token*.
570 ///
571 /// Note that if this token is a `Group` then this method will not configure
572 /// the span of each of the internal tokens, this will simply delegate to
573 /// the `set_span` method of each variant.
574pub fn set_span(&mut self, span: Span) {
575match self {
576 TokenTree::Group(t) => t.set_span(span),
577 TokenTree::Ident(t) => t.set_span(span),
578 TokenTree::Punct(t) => t.set_span(span),
579 TokenTree::Literal(t) => t.set_span(span),
580 }
581 }
582}
583584impl From<Group> for TokenTree {
585fn from(g: Group) -> Self {
586 TokenTree::Group(g)
587 }
588}
589590impl From<Ident> for TokenTree {
591fn from(g: Ident) -> Self {
592 TokenTree::Ident(g)
593 }
594}
595596impl From<Punct> for TokenTree {
597fn from(g: Punct) -> Self {
598 TokenTree::Punct(g)
599 }
600}
601602impl From<Literal> for TokenTree {
603fn from(g: Literal) -> Self {
604 TokenTree::Literal(g)
605 }
606}
607608/// Prints the token tree as a string that is supposed to be losslessly
609/// convertible back into the same token tree (modulo spans), except for
610/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
611/// numeric literals.
612impl Displayfor TokenTree {
613fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
614match self {
615 TokenTree::Group(t) => Display::fmt(t, f),
616 TokenTree::Ident(t) => Display::fmt(t, f),
617 TokenTree::Punct(t) => Display::fmt(t, f),
618 TokenTree::Literal(t) => Display::fmt(t, f),
619 }
620 }
621}
622623/// Prints token tree in a form convenient for debugging.
624impl Debugfor TokenTree {
625fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
626// Each of these has the name in the struct type in the derived debug,
627 // so don't bother with an extra layer of indirection
628match self {
629 TokenTree::Group(t) => Debug::fmt(t, f),
630 TokenTree::Ident(t) => {
631let mut debug = f.debug_struct("Ident");
632debug.field("sym", &format_args!("{0}", t)format_args!("{}", t));
633 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
634debug.finish()
635 }
636 TokenTree::Punct(t) => Debug::fmt(t, f),
637 TokenTree::Literal(t) => Debug::fmt(t, f),
638 }
639 }
640}
641642/// A delimited token stream.
643///
644/// A `Group` internally contains a `TokenStream` which is surrounded by
645/// `Delimiter`s.
646#[derive(#[automatically_derived]
impl ::core::clone::Clone for Group {
#[inline]
fn clone(&self) -> Group {
Group { inner: ::core::clone::Clone::clone(&self.inner) }
}
}Clone)]
647pub struct Group {
648 inner: imp::Group,
649}
650651/// Describes how a sequence of token trees is delimited.
652#[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)]
653pub enum Delimiter {
654/// `( ... )`
655Parenthesis,
656/// `{ ... }`
657Brace,
658/// `[ ... ]`
659Bracket,
660/// `∅ ... ∅`
661 ///
662 /// An invisible delimiter, that may, for example, appear around tokens
663 /// coming from a "macro variable" `$var`. It is important to preserve
664 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
665 /// Invisible delimiters may not survive roundtrip of a token stream through
666 /// a string.
667 ///
668 /// <div class="warning">
669 ///
670 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
671 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
672 /// of a proc_macro macro are preserved, and only in very specific circumstances.
673 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
674 /// operator priorities as indicated above. The other `Delimiter` variants should be used
675 /// instead in this context. This is a rustc bug. For details, see
676 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
677 ///
678 /// </div>
679None,
680}
681682impl Group {
683fn _new(inner: imp::Group) -> Self {
684Group { inner }
685 }
686687fn _new_fallback(inner: fallback::Group) -> Self {
688Group {
689 inner: imp::Group::from(inner),
690 }
691 }
692693/// Creates a new `Group` with the given delimiter and token stream.
694 ///
695 /// This constructor will set the span for this group to
696 /// `Span::call_site()`. To change the span you can use the `set_span`
697 /// method below.
698pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
699Group {
700 inner: imp::Group::new(delimiter, stream.inner),
701 }
702 }
703704/// Returns the punctuation used as the delimiter for this group: a set of
705 /// parentheses, square brackets, or curly braces.
706pub fn delimiter(&self) -> Delimiter {
707self.inner.delimiter()
708 }
709710/// Returns the `TokenStream` of tokens that are delimited in this `Group`.
711 ///
712 /// Note that the returned token stream does not include the delimiter
713 /// returned above.
714pub fn stream(&self) -> TokenStream {
715TokenStream::_new(self.inner.stream())
716 }
717718/// Returns the span for the delimiters of this token stream, spanning the
719 /// entire `Group`.
720 ///
721 /// ```text
722 /// pub fn span(&self) -> Span {
723 /// ^^^^^^^
724 /// ```
725pub fn span(&self) -> Span {
726Span::_new(self.inner.span())
727 }
728729/// Returns the span pointing to the opening delimiter of this group.
730 ///
731 /// ```text
732 /// pub fn span_open(&self) -> Span {
733 /// ^
734 /// ```
735pub fn span_open(&self) -> Span {
736Span::_new(self.inner.span_open())
737 }
738739/// Returns the span pointing to the closing delimiter of this group.
740 ///
741 /// ```text
742 /// pub fn span_close(&self) -> Span {
743 /// ^
744 /// ```
745pub fn span_close(&self) -> Span {
746Span::_new(self.inner.span_close())
747 }
748749/// Returns an object that holds this group's `span_open()` and
750 /// `span_close()` together (in a more compact representation than holding
751 /// those 2 spans individually).
752pub fn delim_span(&self) -> DelimSpan {
753DelimSpan::new(&self.inner)
754 }
755756/// Configures the span for this `Group`'s delimiters, but not its internal
757 /// tokens.
758 ///
759 /// This method will **not** set the span of all the internal tokens spanned
760 /// by this group, but rather it will only set the span of the delimiter
761 /// tokens at the level of the `Group`.
762pub fn set_span(&mut self, span: Span) {
763self.inner.set_span(span.inner);
764 }
765}
766767/// Prints the group as a string that should be losslessly convertible back
768/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
769/// with `Delimiter::None` delimiters.
770impl Displayfor Group {
771fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
772 Display::fmt(&self.inner, formatter)
773 }
774}
775776impl Debugfor Group {
777fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
778 Debug::fmt(&self.inner, formatter)
779 }
780}
781782/// A `Punct` is a single punctuation character like `+`, `-` or `#`.
783///
784/// Multicharacter operators like `+=` are represented as two instances of
785/// `Punct` with different forms of `Spacing` returned.
786#[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)]
787pub struct Punct {
788 ch: char,
789 spacing: Spacing,
790 span: Span,
791}
792793/// Whether a `Punct` is followed immediately by another `Punct` or followed by
794/// another token or whitespace.
795#[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)]
796pub enum Spacing {
797/// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
798Alone,
799/// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.
800 ///
801 /// Additionally, single quote `'` can join with identifiers to form
802 /// lifetimes `'ident`.
803Joint,
804}
805806impl Punct {
807/// Creates a new `Punct` from the given character and spacing.
808 ///
809 /// The `ch` argument must be a valid punctuation character permitted by the
810 /// language, otherwise the function will panic.
811 ///
812 /// The returned `Punct` will have the default span of `Span::call_site()`
813 /// which can be further configured with the `set_span` method below.
814pub fn new(ch: char, spacing: Spacing) -> Self {
815if let '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';'
816| '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch817 {
818Punct {
819ch,
820spacing,
821 span: Span::call_site(),
822 }
823 } else {
824{
::core::panicking::panic_fmt(format_args!("unsupported proc macro punctuation character {0:?}",
ch));
};panic!("unsupported proc macro punctuation character {:?}", ch);
825 }
826 }
827828/// Returns the value of this punctuation character as `char`.
829pub fn as_char(&self) -> char {
830self.ch
831 }
832833/// Returns the spacing of this punctuation character, indicating whether
834 /// it's immediately followed by another `Punct` in the token stream, so
835 /// they can potentially be combined into a multicharacter operator
836 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
837 /// so the operator has certainly ended.
838pub fn spacing(&self) -> Spacing {
839self.spacing
840 }
841842/// Returns the span for this punctuation character.
843pub fn span(&self) -> Span {
844self.span
845 }
846847/// Configure the span for this punctuation character.
848pub fn set_span(&mut self, span: Span) {
849self.span = span;
850 }
851}
852853/// Prints the punctuation character as a string that should be losslessly
854/// convertible back into the same character.
855impl Displayfor Punct {
856fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
857 Display::fmt(&self.ch, f)
858 }
859}
860861impl Debugfor Punct {
862fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
863let mut debug = fmt.debug_struct("Punct");
864debug.field("char", &self.ch);
865debug.field("spacing", &self.spacing);
866 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
867debug.finish()
868 }
869}
870871/// A word of Rust code, which may be a keyword or legal variable name.
872///
873/// An identifier consists of at least one Unicode code point, the first of
874/// which has the XID_Start property and the rest of which have the XID_Continue
875/// property.
876///
877/// - The empty string is not an identifier. Use `Option<Ident>`.
878/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
879///
880/// An identifier constructed with `Ident::new` is permitted to be a Rust
881/// keyword, though parsing one through its [`Parse`] implementation rejects
882/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
883/// behaviour of `Ident::new`.
884///
885/// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html
886///
887/// # Examples
888///
889/// A new ident can be created from a string using the `Ident::new` function.
890/// A span must be provided explicitly which governs the name resolution
891/// behavior of the resulting identifier.
892///
893/// ```
894/// use proc_macro2::{Ident, Span};
895///
896/// fn main() {
897/// let call_ident = Ident::new("calligraphy", Span::call_site());
898///
899/// println!("{}", call_ident);
900/// }
901/// ```
902///
903/// An ident can be interpolated into a token stream using the `quote!` macro.
904///
905/// ```
906/// use proc_macro2::{Ident, Span};
907/// use quote::quote;
908///
909/// fn main() {
910/// let ident = Ident::new("demo", Span::call_site());
911///
912/// // Create a variable binding whose name is this ident.
913/// let expanded = quote! { let #ident = 10; };
914///
915/// // Create a variable binding with a slightly different name.
916/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
917/// let expanded = quote! { let #temp_ident = 10; };
918/// }
919/// ```
920///
921/// A string representation of the ident is available through the `to_string()`
922/// method.
923///
924/// ```
925/// # use proc_macro2::{Ident, Span};
926/// #
927/// # let ident = Ident::new("another_identifier", Span::call_site());
928/// #
929/// // Examine the ident as a string.
930/// let ident_string = ident.to_string();
931/// if ident_string.len() > 60 {
932/// println!("Very long identifier: {}", ident_string)
933/// }
934/// ```
935#[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)]
936pub struct Ident {
937 inner: imp::Ident,
938 _marker: ProcMacroAutoTraits,
939}
940941impl Ident {
942fn _new(inner: imp::Ident) -> Self {
943Ident {
944inner,
945 _marker: MARKER,
946 }
947 }
948949fn _new_fallback(inner: fallback::Ident) -> Self {
950Ident {
951 inner: imp::Ident::from(inner),
952 _marker: MARKER,
953 }
954 }
955956/// Creates a new `Ident` with the given `string` as well as the specified
957 /// `span`.
958 ///
959 /// The `string` argument must be a valid identifier permitted by the
960 /// language, otherwise the function will panic.
961 ///
962 /// Note that `span`, currently in rustc, configures the hygiene information
963 /// for this identifier.
964 ///
965 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
966 /// hygiene meaning that identifiers created with this span will be resolved
967 /// as if they were written directly at the location of the macro call, and
968 /// other code at the macro call site will be able to refer to them as well.
969 ///
970 /// Later spans like `Span::def_site()` will allow to opt-in to
971 /// "definition-site" hygiene meaning that identifiers created with this
972 /// span will be resolved at the location of the macro definition and other
973 /// code at the macro call site will not be able to refer to them.
974 ///
975 /// Due to the current importance of hygiene this constructor, unlike other
976 /// tokens, requires a `Span` to be specified at construction.
977 ///
978 /// # Panics
979 ///
980 /// Panics if the input string is neither a keyword nor a legal variable
981 /// name. If you are not sure whether the string contains an identifier and
982 /// need to handle an error case, use
983 /// <a href="https://docs.rs/syn/2.0/syn/fn.parse_str.html"><code
984 /// style="padding-right:0;">syn::parse_str</code></a><code
985 /// style="padding-left:0;">::<Ident></code>
986 /// rather than `Ident::new`.
987#[track_caller]
988pub fn new(string: &str, span: Span) -> Self {
989Ident::_new(imp::Ident::new_checked(string, span.inner))
990 }
991992/// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The
993 /// `string` argument must be a valid identifier permitted by the language
994 /// (including keywords, e.g. `fn`). Keywords which are usable in path
995 /// segments (e.g. `self`, `super`) are not supported, and will cause a
996 /// panic.
997#[track_caller]
998pub fn new_raw(string: &str, span: Span) -> Self {
999Ident::_new(imp::Ident::new_raw_checked(string, span.inner))
1000 }
10011002/// Returns the span of this `Ident`.
1003pub fn span(&self) -> Span {
1004Span::_new(self.inner.span())
1005 }
10061007/// Configures the span of this `Ident`, possibly changing its hygiene
1008 /// context.
1009pub fn set_span(&mut self, span: Span) {
1010self.inner.set_span(span.inner);
1011 }
1012}
10131014impl PartialEqfor Ident {
1015fn eq(&self, other: &Ident) -> bool {
1016self.inner == other.inner
1017 }
1018}
10191020impl<T> PartialEq<T> for Ident1021where
1022T: ?Sized + AsRef<str>,
1023{
1024fn eq(&self, other: &T) -> bool {
1025self.inner == other1026 }
1027}
10281029impl Eqfor Ident {}
10301031impl PartialOrdfor Ident {
1032fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
1033Some(self.cmp(other))
1034 }
1035}
10361037impl Ordfor Ident {
1038fn cmp(&self, other: &Ident) -> Ordering {
1039self.to_string().cmp(&other.to_string())
1040 }
1041}
10421043impl Hashfor Ident {
1044fn hash<H: Hasher>(&self, hasher: &mut H) {
1045self.to_string().hash(hasher);
1046 }
1047}
10481049/// Prints the identifier as a string that should be losslessly convertible back
1050/// into the same identifier.
1051impl Displayfor Ident {
1052fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1053 Display::fmt(&self.inner, f)
1054 }
1055}
10561057impl Debugfor Ident {
1058fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1059 Debug::fmt(&self.inner, f)
1060 }
1061}
10621063/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
1064/// byte character (`b'a'`), an integer or floating point number with or without
1065/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1066///
1067/// Boolean literals like `true` and `false` do not belong here, they are
1068/// `Ident`s.
1069#[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)]
1070pub struct Literal {
1071 inner: imp::Literal,
1072 _marker: ProcMacroAutoTraits,
1073}
10741075macro_rules! suffixed_int_literals {
1076 ($($name:ident => $kind:ident,)*) => ($(
1077/// Creates a new suffixed integer literal with the specified value.
1078 ///
1079 /// This function will create an integer like `1u32` where the integer
1080 /// value specified is the first part of the token and the integral is
1081 /// also suffixed at the end. Literals created from negative numbers may
1082 /// not survive roundtrips through `TokenStream` or strings and may be
1083 /// broken into two tokens (`-` and positive literal).
1084 ///
1085 /// Literals created through this method have the `Span::call_site()`
1086 /// span by default, which can be configured with the `set_span` method
1087 /// below.
1088pub fn $name(n: $kind) -> Literal {
1089 Literal::_new(imp::Literal::$name(n))
1090 }
1091 )*)
1092}
10931094macro_rules! unsuffixed_int_literals {
1095 ($($name:ident => $kind:ident,)*) => ($(
1096/// Creates a new unsuffixed integer literal with the specified value.
1097 ///
1098 /// This function will create an integer like `1` where the integer
1099 /// value specified is the first part of the token. No suffix is
1100 /// specified on this token, meaning that invocations like
1101 /// `Literal::i8_unsuffixed(1)` are equivalent to
1102 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
1103 /// may not survive roundtrips through `TokenStream` or strings and may
1104 /// be broken into two tokens (`-` and positive literal).
1105 ///
1106 /// Literals created through this method have the `Span::call_site()`
1107 /// span by default, which can be configured with the `set_span` method
1108 /// below.
1109pub fn $name(n: $kind) -> Literal {
1110 Literal::_new(imp::Literal::$name(n))
1111 }
1112 )*)
1113}
11141115impl Literal {
1116fn _new(inner: imp::Literal) -> Self {
1117Literal {
1118inner,
1119 _marker: MARKER,
1120 }
1121 }
11221123fn _new_fallback(inner: fallback::Literal) -> Self {
1124Literal {
1125 inner: imp::Literal::from(inner),
1126 _marker: MARKER,
1127 }
1128 }
11291130n
Literal::_new(imp::Literal::isize_suffixed(n));suffixed_int_literals! {
1131 u8_suffixed => u8,
1132 u16_suffixed => u16,
1133 u32_suffixed => u32,
1134 u64_suffixed => u64,
1135 u128_suffixed => u128,
1136 usize_suffixed => usize,
1137 i8_suffixed => i8,
1138 i16_suffixed => i16,
1139 i32_suffixed => i32,
1140 i64_suffixed => i64,
1141 i128_suffixed => i128,
1142 isize_suffixed => isize,
1143 }11441145n
Literal::_new(imp::Literal::isize_unsuffixed(n));unsuffixed_int_literals! {
1146 u8_unsuffixed => u8,
1147 u16_unsuffixed => u16,
1148 u32_unsuffixed => u32,
1149 u64_unsuffixed => u64,
1150 u128_unsuffixed => u128,
1151 usize_unsuffixed => usize,
1152 i8_unsuffixed => i8,
1153 i16_unsuffixed => i16,
1154 i32_unsuffixed => i32,
1155 i64_unsuffixed => i64,
1156 i128_unsuffixed => i128,
1157 isize_unsuffixed => isize,
1158 }11591160/// Creates a new unsuffixed floating-point literal.
1161 ///
1162 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1163 /// the float's value is emitted directly into the token but no suffix is
1164 /// used, so it may be inferred to be a `f64` later in the compiler.
1165 /// Literals created from negative numbers may not survive round-trips
1166 /// through `TokenStream` or strings and may be broken into two tokens (`-`
1167 /// and positive literal).
1168 ///
1169 /// # Panics
1170 ///
1171 /// This function requires that the specified float is finite, for example
1172 /// if it is infinity or NaN this function will panic.
1173pub fn f64_unsuffixed(f: f64) -> Literal {
1174if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1175Literal::_new(imp::Literal::f64_unsuffixed(f))
1176 }
11771178/// Creates a new suffixed floating-point literal.
1179 ///
1180 /// This constructor will create a literal like `1.0f64` where the value
1181 /// specified is the preceding part of the token and `f64` is the suffix of
1182 /// the token. This token will always be inferred to be an `f64` in the
1183 /// compiler. Literals created from negative numbers may not survive
1184 /// round-trips through `TokenStream` or strings and may be broken into two
1185 /// tokens (`-` and positive literal).
1186 ///
1187 /// # Panics
1188 ///
1189 /// This function requires that the specified float is finite, for example
1190 /// if it is infinity or NaN this function will panic.
1191pub fn f64_suffixed(f: f64) -> Literal {
1192if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1193Literal::_new(imp::Literal::f64_suffixed(f))
1194 }
11951196/// Creates a new unsuffixed floating-point literal.
1197 ///
1198 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1199 /// the float's value is emitted directly into the token but no suffix is
1200 /// used, so it may be inferred to be a `f64` later in the compiler.
1201 /// Literals created from negative numbers may not survive round-trips
1202 /// through `TokenStream` or strings and may be broken into two tokens (`-`
1203 /// and positive literal).
1204 ///
1205 /// # Panics
1206 ///
1207 /// This function requires that the specified float is finite, for example
1208 /// if it is infinity or NaN this function will panic.
1209pub fn f32_unsuffixed(f: f32) -> Literal {
1210if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1211Literal::_new(imp::Literal::f32_unsuffixed(f))
1212 }
12131214/// Creates a new suffixed floating-point literal.
1215 ///
1216 /// This constructor will create a literal like `1.0f32` where the value
1217 /// specified is the preceding part of the token and `f32` is the suffix of
1218 /// the token. This token will always be inferred to be an `f32` in the
1219 /// compiler. Literals created from negative numbers may not survive
1220 /// round-trips through `TokenStream` or strings and may be broken into two
1221 /// tokens (`-` and positive literal).
1222 ///
1223 /// # Panics
1224 ///
1225 /// This function requires that the specified float is finite, for example
1226 /// if it is infinity or NaN this function will panic.
1227pub fn f32_suffixed(f: f32) -> Literal {
1228if !f.is_finite() {
::core::panicking::panic("assertion failed: f.is_finite()")
};assert!(f.is_finite());
1229Literal::_new(imp::Literal::f32_suffixed(f))
1230 }
12311232/// String literal.
1233pub fn string(string: &str) -> Literal {
1234Literal::_new(imp::Literal::string(string))
1235 }
12361237/// Character literal.
1238pub fn character(ch: char) -> Literal {
1239Literal::_new(imp::Literal::character(ch))
1240 }
12411242/// Byte character literal.
1243pub fn byte_character(byte: u8) -> Literal {
1244Literal::_new(imp::Literal::byte_character(byte))
1245 }
12461247/// Byte string literal.
1248pub fn byte_string(bytes: &[u8]) -> Literal {
1249Literal::_new(imp::Literal::byte_string(bytes))
1250 }
12511252/// C string literal.
1253pub fn c_string(string: &CStr) -> Literal {
1254Literal::_new(imp::Literal::c_string(string))
1255 }
12561257/// Returns the span encompassing this literal.
1258pub fn span(&self) -> Span {
1259Span::_new(self.inner.span())
1260 }
12611262/// Configures the span associated for this literal.
1263pub fn set_span(&mut self, span: Span) {
1264self.inner.set_span(span.inner);
1265 }
12661267/// Returns a `Span` that is a subset of `self.span()` containing only
1268 /// the source bytes in range `range`. Returns `None` if the would-be
1269 /// trimmed span is outside the bounds of `self`.
1270 ///
1271 /// Warning: the underlying [`proc_macro::Literal::subspan`] method is
1272 /// nightly-only. When called from within a procedural macro not using a
1273 /// nightly compiler, this method will always return `None`.
1274pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1275self.inner.subspan(range).map(Span::_new)
1276 }
12771278/// Returns the unescaped string value if this is a string literal.
1279#[cfg(procmacro2_semver_exempt)]
1280pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1281let repr = self.to_string();
12821283if repr.starts_with('"') && repr[1..].ends_with('"') {
1284let quoted = &repr[1..repr.len() - 1];
1285let mut value = String::with_capacity(quoted.len());
1286let mut error = None;
1287 rustc_literal_escaper::unescape_str(quoted, |_range, res| match res {
1288Ok(ch) => value.push(ch),
1289Err(err) => {
1290if err.is_fatal() {
1291 error = Some(ConversionErrorKind::FailedToUnescape(err));
1292 }
1293 }
1294 });
1295return match error {
1296Some(error) => Err(error),
1297None => Ok(value),
1298 };
1299 }
13001301if repr.starts_with('r') {
1302if let Some(raw) = get_raw(&repr[1..]) {
1303return Ok(raw.to_owned());
1304 }
1305 }
13061307Err(ConversionErrorKind::InvalidLiteralKind)
1308 }
13091310/// Returns the unescaped string value (including nul terminator) if this is
1311 /// a c-string literal.
1312#[cfg(procmacro2_semver_exempt)]
1313pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1314let repr = self.to_string();
13151316if repr.starts_with("c\"") && repr[2..].ends_with('"') {
1317let quoted = &repr[2..repr.len() - 1];
1318let mut value = Vec::with_capacity(quoted.len());
1319let mut error = None;
1320 rustc_literal_escaper::unescape_c_str(quoted, |_range, res| match res {
1321Ok(MixedUnit::Char(ch)) => {
1322 value.extend_from_slice(ch.get().encode_utf8(&mut [0; 4]).as_bytes());
1323 }
1324Ok(MixedUnit::HighByte(byte)) => value.push(byte.get()),
1325Err(err) => {
1326if err.is_fatal() {
1327 error = Some(ConversionErrorKind::FailedToUnescape(err));
1328 }
1329 }
1330 });
1331return match error {
1332Some(error) => Err(error),
1333None => {
1334 value.push(b'\0');
1335Ok(value)
1336 }
1337 };
1338 }
13391340if repr.starts_with("cr") {
1341if let Some(raw) = get_raw(&repr[2..]) {
1342let mut value = Vec::with_capacity(raw.len() + 1);
1343 value.extend_from_slice(raw.as_bytes());
1344 value.push(b'\0');
1345return Ok(value);
1346 }
1347 }
13481349Err(ConversionErrorKind::InvalidLiteralKind)
1350 }
13511352/// Returns the unescaped string value if this is a byte string literal.
1353#[cfg(procmacro2_semver_exempt)]
1354pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1355let repr = self.to_string();
13561357if repr.starts_with("b\"") && repr[2..].ends_with('"') {
1358let quoted = &repr[2..repr.len() - 1];
1359let mut value = Vec::with_capacity(quoted.len());
1360let mut error = None;
1361 rustc_literal_escaper::unescape_byte_str(quoted, |_range, res| match res {
1362Ok(byte) => value.push(byte),
1363Err(err) => {
1364if err.is_fatal() {
1365 error = Some(ConversionErrorKind::FailedToUnescape(err));
1366 }
1367 }
1368 });
1369return match error {
1370Some(error) => Err(error),
1371None => Ok(value),
1372 };
1373 }
13741375if repr.starts_with("br") {
1376if let Some(raw) = get_raw(&repr[2..]) {
1377return Ok(raw.as_bytes().to_owned());
1378 }
1379 }
13801381Err(ConversionErrorKind::InvalidLiteralKind)
1382 }
13831384// Intended for the `quote!` macro to use when constructing a proc-macro2
1385 // token out of a macro_rules $:literal token, which is already known to be
1386 // a valid literal. This avoids reparsing/validating the literal's string
1387 // representation. This is not public API other than for quote.
1388#[doc(hidden)]
1389pub unsafe fn from_str_unchecked(repr: &str) -> Self {
1390Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })
1391 }
1392}
13931394impl FromStrfor Literal {
1395type Err = LexError;
13961397fn from_str(repr: &str) -> Result<Self, LexError> {
1398match imp::Literal::from_str_checked(repr) {
1399Ok(lit) => Ok(Literal::_new(lit)),
1400Err(lex) => Err(LexError {
1401 inner: lex,
1402 _marker: MARKER,
1403 }),
1404 }
1405 }
1406}
14071408impl Debugfor Literal {
1409fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1410 Debug::fmt(&self.inner, f)
1411 }
1412}
14131414impl Displayfor Literal {
1415fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1416 Display::fmt(&self.inner, f)
1417 }
1418}
14191420/// Error when retrieving a string literal's unescaped value.
1421#[cfg(procmacro2_semver_exempt)]
1422#[derive(Debug, PartialEq, Eq)]
1423pub enum ConversionErrorKind {
1424/// The literal is of the right string kind, but its contents are malformed
1425 /// in a way that cannot be unescaped to a value.
1426FailedToUnescape(EscapeError),
1427/// The literal is not of the string kind whose value was requested, for
1428 /// example byte string vs UTF-8 string.
1429InvalidLiteralKind,
1430}
14311432// ###"..."### -> ...
1433#[cfg(procmacro2_semver_exempt)]
1434fn get_raw(repr: &str) -> Option<&str> {
1435let pounds = repr.len() - repr.trim_start_matches('#').len();
1436if repr.len() >= pounds + 1 + 1 + pounds
1437 && repr[pounds..].starts_with('"')
1438 && repr.trim_end_matches('#').len() + pounds == repr.len()
1439 && repr[..repr.len() - pounds].ends_with('"')
1440 {
1441Some(&repr[pounds + 1..repr.len() - pounds - 1])
1442 } else {
1443None
1444}
1445}
14461447/// Public implementation details for the `TokenStream` type, such as iterators.
1448pub mod token_stream {
1449use crate::marker::{ProcMacroAutoTraits, MARKER};
1450use crate::{imp, TokenTree};
1451use core::fmt::{self, Debug};
14521453pub use crate::TokenStream;
14541455/// An iterator over `TokenStream`'s `TokenTree`s.
1456 ///
1457 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1458 /// delimited groups, and returns whole groups as token trees.
1459#[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)]
1460pub struct IntoIter {
1461 inner: imp::TokenTreeIter,
1462 _marker: ProcMacroAutoTraits,
1463 }
14641465impl Iteratorfor IntoIter {
1466type Item = TokenTree;
14671468fn next(&mut self) -> Option<TokenTree> {
1469self.inner.next()
1470 }
14711472fn size_hint(&self) -> (usize, Option<usize>) {
1473self.inner.size_hint()
1474 }
1475 }
14761477impl Debugfor IntoIter {
1478fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1479f.write_str("TokenStream ")?;
1480f.debug_list().entries(self.clone()).finish()
1481 }
1482 }
14831484impl IntoIteratorfor TokenStream {
1485type Item = TokenTree;
1486type IntoIter = IntoIter;
14871488fn into_iter(self) -> IntoIter {
1489IntoIter {
1490 inner: self.inner.into_iter(),
1491 _marker: MARKER,
1492 }
1493 }
1494 }
1495}