// SPDX-License-Identifier: Apache-2.0 OR MIT12//! [![github]](https://github.com/dtolnay/proc-macro2) [![crates-io]](https://crates.io/crates/proc-macro2) [![docs-rs]](crate)3//!4//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github5//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust6//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs7//!8//! <br>9//!10//! A wrapper around the procedural macro API of the compiler's [`proc_macro`]11//! crate. This library serves two purposes:12//!13//! - **Bring proc-macro-like functionality to other contexts like build.rs and14//! main.rs.** Types from `proc_macro` are entirely specific to procedural15//! macros and cannot ever exist in code outside of a procedural macro.16//! Meanwhile `proc_macro2` types may exist anywhere including non-macro code.17//! By developing foundational libraries like [syn] and [quote] against18//! `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem19//! becomes easily applicable to many other use cases and we avoid20//! reimplementing non-macro equivalents of those libraries.21//!22//! - **Make procedural macros unit testable.** As a consequence of being23//! specific to procedural macros, nothing that uses `proc_macro` can be24//! executed from a unit test. In order for helper libraries or components of25//! a macro to be testable in isolation, they must be implemented using26//! `proc_macro2`.27//!28//! [syn]: https://github.com/dtolnay/syn29//! [quote]: https://github.com/dtolnay/quote30//!31//! # Usage32//!33//! The skeleton of a typical procedural macro typically looks like this:34//!35//! ```36//! extern crate proc_macro;37//!38//! # const IGNORE: &str = stringify! {39//! #[proc_macro_derive(MyDerive)]40//! # };41//! # #[cfg(wrap_proc_macro)]42//! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {43//! let input = proc_macro2::TokenStream::from(input);44//!45//! let output: proc_macro2::TokenStream = {46//! /* transform input */47//! # input48//! };49//!50//! proc_macro::TokenStream::from(output)51//! }52//! ```53//!54//! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to55//! propagate parse errors correctly back to the compiler when parsing fails.56//!57//! [`parse_macro_input!`]: https://docs.rs/syn/2.0/syn/macro.parse_macro_input.html58//!59//! # Unstable features60//!61//! The default feature set of proc-macro2 tracks the most recent stable62//! compiler API. Functionality in `proc_macro` that is not yet stable is not63//! exposed by proc-macro2 by default.64//!65//! To opt into the additional APIs available in the most recent nightly66//! compiler, the `procmacro2_semver_exempt` config flag must be passed to67//! rustc. We will polyfill those nightly-only APIs back to Rust 1.56.0. As68//! these are unstable APIs that track the nightly compiler, minor versions of69//! proc-macro2 may make breaking changes to them at any time.70//!71//! ```sh72//! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build73//! ```74//!75//! Note that this must not only be done for your crate, but for any crate that76//! depends on your crate. This infectious nature is intentional, as it serves77//! as a reminder that you are outside of the normal semver guarantees.78//!79//! Semver exempt methods are marked as such in the proc-macro2 documentation.80//!81//! # Thread-Safety82//!83//! Most types in this crate are `!Sync` because the underlying compiler84//! types make use of thread-local memory, meaning they cannot be accessed from85//! a different thread.8687// Proc-macro2 types in rustdoc of other crates get linked to here.88#![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.101")]89#![cfg_attr(any(proc_macro_span, super_unstable), feature(proc_macro_span))]90#![cfg_attr(super_unstable, feature(proc_macro_def_site))]91#![cfg_attr(docsrs, feature(doc_cfg))]92#![deny(unsafe_op_in_unsafe_fn)]93#![allow(94clippy::cast_lossless,95clippy::cast_possible_truncation,96clippy::checked_conversions,97clippy::doc_markdown,98clippy::elidable_lifetime_names,99clippy::incompatible_msrv,100clippy::items_after_statements,101clippy::iter_without_into_iter,102clippy::let_underscore_untyped,103clippy::manual_assert,104clippy::manual_range_contains,105clippy::missing_panics_doc,106clippy::missing_safety_doc,107clippy::must_use_candidate,108clippy::needless_doctest_main,109clippy::needless_lifetimes,110clippy::new_without_default,111clippy::return_self_not_must_use,112clippy::shadow_unrelated,113clippy::trivially_copy_pass_by_ref,114clippy::unnecessary_wraps,115clippy::unused_self,116clippy::used_underscore_binding,117clippy::vec_init_then_push118)]119#![allow(unknown_lints, mismatched_lifetime_syntaxes)]120121#[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))]122compile_error! {"\123Something is not right. If you've tried to turn on \124procmacro2_semver_exempt, you need to ensure that it \125is turned on for the compilation of the proc-macro2 \126build script as well.127"}128129#[cfg(all(130procmacro2_nightly_testing,131feature = "proc-macro",132not(proc_macro_span)133))]134compile_error! {"\135Build 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 quite152// 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;166167use crate::extra::DelimSpan;168use crate::marker::{ProcMacroAutoTraits, MARKER};169use core::cmp::Ordering;170use core::fmt::{self, Debug, Display};171use core::hash::{Hash, Hasher};172#[cfg(span_locations)]173use core::ops::Range;174use core::ops::RangeBounds;175use core::str::FromStr;176use std::error::Error;177use std::ffi::CStr;178#[cfg(span_locations)]179use std::path::PathBuf;180181#[cfg(span_locations)]182#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]183pub use crate::location::LineColumn;184185/// An abstract stream of tokens, or more concretely a sequence of token trees.186///187/// This type provides interfaces for iterating over token trees and for188/// collecting token trees into one stream.189///190/// Token stream is both the input and output of `#[proc_macro]`,191/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.192#[derive(Clone)]193pub struct TokenStream {194inner: imp::TokenStream,195_marker: ProcMacroAutoTraits,196}197198/// Error returned from `TokenStream::from_str`.199pub struct LexError {200inner: imp::LexError,201_marker: ProcMacroAutoTraits,202}203204impl TokenStream {205fn _new(inner: imp::TokenStream) -> Self {206TokenStream {207inner,208_marker: MARKER,209}210}211212fn _new_fallback(inner: fallback::TokenStream) -> Self {213TokenStream {214inner: imp::TokenStream::from(inner),215_marker: MARKER,216}217}218219/// Returns an empty `TokenStream` containing no token trees.220pub fn new() -> Self {221TokenStream::_new(imp::TokenStream::new())222}223224/// Checks if this `TokenStream` is empty.225pub fn is_empty(&self) -> bool {226self.inner.is_empty()227}228}229230/// `TokenStream::default()` returns an empty stream,231/// i.e. this is equivalent with `TokenStream::new()`.232impl Default for TokenStream {233fn default() -> Self {234TokenStream::new()235}236}237238/// Attempts to break the string into tokens and parse those tokens into a token239/// stream.240///241/// May fail for a number of reasons, for example, if the string contains242/// unbalanced delimiters or characters not existing in the language.243///244/// NOTE: Some errors may cause panics instead of returning `LexError`. We245/// reserve the right to change these errors into `LexError`s later.246impl FromStr for TokenStream {247type Err = LexError;248249fn from_str(src: &str) -> Result<TokenStream, LexError> {250match imp::TokenStream::from_str_checked(src) {251Ok(tokens) => Ok(TokenStream::_new(tokens)),252Err(lex) => Err(LexError {253inner: lex,254_marker: MARKER,255}),256}257}258}259260#[cfg(feature = "proc-macro")]261#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]262impl From<proc_macro::TokenStream> for TokenStream {263fn from(inner: proc_macro::TokenStream) -> Self {264TokenStream::_new(imp::TokenStream::from(inner))265}266}267268#[cfg(feature = "proc-macro")]269#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]270impl From<TokenStream> for proc_macro::TokenStream {271fn from(inner: TokenStream) -> Self {272proc_macro::TokenStream::from(inner.inner)273}274}275276impl From<TokenTree> for TokenStream {277fn from(token: TokenTree) -> Self {278TokenStream::_new(imp::TokenStream::from(token))279}280}281282impl Extend<TokenTree> for TokenStream {283fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {284self.inner.extend(streams);285}286}287288impl Extend<TokenStream> for TokenStream {289fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {290self.inner291.extend(streams.into_iter().map(|stream| stream.inner));292}293}294295/// Collects a number of token trees into a single stream.296impl FromIterator<TokenTree> for TokenStream {297fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {298TokenStream::_new(streams.into_iter().collect())299}300}301impl FromIterator<TokenStream> for TokenStream {302fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {303TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())304}305}306307/// Prints the token stream as a string that is supposed to be losslessly308/// convertible back into the same token stream (modulo spans), except for309/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative310/// numeric literals.311impl Display for TokenStream {312fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {313Display::fmt(&self.inner, f)314}315}316317/// Prints token in a form convenient for debugging.318impl Debug for TokenStream {319fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {320Debug::fmt(&self.inner, f)321}322}323324impl LexError {325pub fn span(&self) -> Span {326Span::_new(self.inner.span())327}328}329330impl Debug for LexError {331fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {332Debug::fmt(&self.inner, f)333}334}335336impl Display for LexError {337fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {338Display::fmt(&self.inner, f)339}340}341342impl Error for LexError {}343344/// A region of source code, along with macro expansion information.345#[derive(Copy, Clone)]346pub struct Span {347inner: imp::Span,348_marker: ProcMacroAutoTraits,349}350351impl Span {352fn _new(inner: imp::Span) -> Self {353Span {354inner,355_marker: MARKER,356}357}358359fn _new_fallback(inner: fallback::Span) -> Self {360Span {361inner: imp::Span::from(inner),362_marker: MARKER,363}364}365366/// The span of the invocation of the current procedural macro.367///368/// Identifiers created with this span will be resolved as if they were369/// written directly at the macro call location (call-site hygiene) and370/// other code at the macro call site will be able to refer to them as well.371pub fn call_site() -> Self {372Span::_new(imp::Span::call_site())373}374375/// The span located at the invocation of the procedural macro, but with376/// local variables, labels, and `$crate` resolved at the definition site377/// of the macro. This is the same hygiene behavior as `macro_rules`.378pub fn mixed_site() -> Self {379Span::_new(imp::Span::mixed_site())380}381382/// A span that resolves at the macro definition site.383///384/// This method is semver exempt and not exposed by default.385#[cfg(procmacro2_semver_exempt)]386#[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]387pub fn def_site() -> Self {388Span::_new(imp::Span::def_site())389}390391/// Creates a new span with the same line/column information as `self` but392/// that resolves symbols as though it were at `other`.393pub fn resolved_at(&self, other: Span) -> Span {394Span::_new(self.inner.resolved_at(other.inner))395}396397/// Creates a new span with the same name resolution behavior as `self` but398/// with the line/column information of `other`.399pub fn located_at(&self, other: Span) -> Span {400Span::_new(self.inner.located_at(other.inner))401}402403/// Convert `proc_macro2::Span` to `proc_macro::Span`.404///405/// This method is available when building with a nightly compiler, or when406/// building with rustc 1.29+ *without* semver exempt features.407///408/// # Panics409///410/// Panics if called from outside of a procedural macro. Unlike411/// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within412/// the context of a procedural macro invocation.413#[cfg(wrap_proc_macro)]414pub fn unwrap(self) -> proc_macro::Span {415self.inner.unwrap()416}417418// Soft deprecated. Please use Span::unwrap.419#[cfg(wrap_proc_macro)]420#[doc(hidden)]421pub fn unstable(self) -> proc_macro::Span {422self.unwrap()423}424425/// Returns the span's byte position range in the source file.426///427/// This method requires the `"span-locations"` feature to be enabled.428///429/// When executing in a procedural macro context, the returned range is only430/// accurate if compiled with a nightly toolchain. The stable toolchain does431/// not have this information available. When executing outside of a432/// procedural macro, such as main.rs or build.rs, the byte range is always433/// accurate regardless of toolchain.434#[cfg(span_locations)]435#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]436pub fn byte_range(&self) -> Range<usize> {437self.inner.byte_range()438}439440/// Get the starting line/column in the source file for this span.441///442/// This method requires the `"span-locations"` feature to be enabled.443///444/// When executing in a procedural macro context, the returned line/column445/// are only meaningful if compiled with a nightly toolchain. The stable446/// toolchain does not have this information available. When executing447/// outside of a procedural macro, such as main.rs or build.rs, the448/// line/column are always meaningful regardless of toolchain.449#[cfg(span_locations)]450#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]451pub fn start(&self) -> LineColumn {452self.inner.start()453}454455/// Get the ending line/column in the source file for this span.456///457/// This method requires the `"span-locations"` feature to be enabled.458///459/// When executing in a procedural macro context, the returned line/column460/// are only meaningful if compiled with a nightly toolchain. The stable461/// toolchain does not have this information available. When executing462/// outside of a procedural macro, such as main.rs or build.rs, the463/// line/column are always meaningful regardless of toolchain.464#[cfg(span_locations)]465#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]466pub fn end(&self) -> LineColumn {467self.inner.end()468}469470/// The path to the source file in which this span occurs, for display471/// purposes.472///473/// This might not correspond to a valid file system path. It might be474/// remapped, or might be an artificial path such as `"<macro expansion>"`.475#[cfg(span_locations)]476#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]477pub fn file(&self) -> String {478self.inner.file()479}480481/// The path to the source file in which this span occurs on disk.482///483/// This is the actual path on disk. It is unaffected by path remapping.484///485/// This path should not be embedded in the output of the macro; prefer486/// `file()` instead.487#[cfg(span_locations)]488#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]489pub fn local_file(&self) -> Option<PathBuf> {490self.inner.local_file()491}492493/// Create a new span encompassing `self` and `other`.494///495/// Returns `None` if `self` and `other` are from different files.496///497/// Warning: the underlying [`proc_macro::Span::join`] method is498/// nightly-only. When called from within a procedural macro not using a499/// nightly compiler, this method will always return `None`.500pub fn join(&self, other: Span) -> Option<Span> {501self.inner.join(other.inner).map(Span::_new)502}503504/// Compares two spans to see if they're equal.505///506/// This method is semver exempt and not exposed by default.507#[cfg(procmacro2_semver_exempt)]508#[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]509pub fn eq(&self, other: &Span) -> bool {510self.inner.eq(&other.inner)511}512513/// Returns the source text behind a span. This preserves the original514/// source code, including spaces and comments. It only returns a result if515/// the span corresponds to real source code.516///517/// Note: The observable result of a macro should only rely on the tokens518/// and not on this source text. The result of this function is a best519/// effort to be used for diagnostics only.520pub fn source_text(&self) -> Option<String> {521self.inner.source_text()522}523}524525/// Prints a span in a form convenient for debugging.526impl Debug for Span {527fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {528Debug::fmt(&self.inner, f)529}530}531532/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).533#[derive(Clone)]534pub enum TokenTree {535/// A token stream surrounded by bracket delimiters.536Group(Group),537/// An identifier.538Ident(Ident),539/// A single punctuation character (`+`, `,`, `$`, etc.).540Punct(Punct),541/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.542Literal(Literal),543}544545impl TokenTree {546/// Returns the span of this tree, delegating to the `span` method of547/// the contained token or a delimited stream.548pub fn span(&self) -> Span {549match self {550TokenTree::Group(t) => t.span(),551TokenTree::Ident(t) => t.span(),552TokenTree::Punct(t) => t.span(),553TokenTree::Literal(t) => t.span(),554}555}556557/// Configures the span for *only this token*.558///559/// Note that if this token is a `Group` then this method will not configure560/// the span of each of the internal tokens, this will simply delegate to561/// the `set_span` method of each variant.562pub fn set_span(&mut self, span: Span) {563match self {564TokenTree::Group(t) => t.set_span(span),565TokenTree::Ident(t) => t.set_span(span),566TokenTree::Punct(t) => t.set_span(span),567TokenTree::Literal(t) => t.set_span(span),568}569}570}571572impl From<Group> for TokenTree {573fn from(g: Group) -> Self {574TokenTree::Group(g)575}576}577578impl From<Ident> for TokenTree {579fn from(g: Ident) -> Self {580TokenTree::Ident(g)581}582}583584impl From<Punct> for TokenTree {585fn from(g: Punct) -> Self {586TokenTree::Punct(g)587}588}589590impl From<Literal> for TokenTree {591fn from(g: Literal) -> Self {592TokenTree::Literal(g)593}594}595596/// Prints the token tree as a string that is supposed to be losslessly597/// convertible back into the same token tree (modulo spans), except for598/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative599/// numeric literals.600impl Display for TokenTree {601fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {602match self {603TokenTree::Group(t) => Display::fmt(t, f),604TokenTree::Ident(t) => Display::fmt(t, f),605TokenTree::Punct(t) => Display::fmt(t, f),606TokenTree::Literal(t) => Display::fmt(t, f),607}608}609}610611/// Prints token tree in a form convenient for debugging.612impl Debug for TokenTree {613fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {614// Each of these has the name in the struct type in the derived debug,615// so don't bother with an extra layer of indirection616match self {617TokenTree::Group(t) => Debug::fmt(t, f),618TokenTree::Ident(t) => {619let mut debug = f.debug_struct("Ident");620debug.field("sym", &format_args!("{}", t));621imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);622debug.finish()623}624TokenTree::Punct(t) => Debug::fmt(t, f),625TokenTree::Literal(t) => Debug::fmt(t, f),626}627}628}629630/// A delimited token stream.631///632/// A `Group` internally contains a `TokenStream` which is surrounded by633/// `Delimiter`s.634#[derive(Clone)]635pub struct Group {636inner: imp::Group,637}638639/// Describes how a sequence of token trees is delimited.640#[derive(Copy, Clone, Debug, Eq, PartialEq)]641pub enum Delimiter {642/// `( ... )`643Parenthesis,644/// `{ ... }`645Brace,646/// `[ ... ]`647Bracket,648/// `∅ ... ∅`649///650/// An invisible delimiter, that may, for example, appear around tokens651/// coming from a "macro variable" `$var`. It is important to preserve652/// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.653/// Invisible delimiters may not survive roundtrip of a token stream through654/// a string.655///656/// <div class="warning">657///658/// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output659/// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input660/// of a proc_macro macro are preserved, and only in very specific circumstances.661/// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve662/// operator priorities as indicated above. The other `Delimiter` variants should be used663/// instead in this context. This is a rustc bug. For details, see664/// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).665///666/// </div>667None,668}669670impl Group {671fn _new(inner: imp::Group) -> Self {672Group { inner }673}674675fn _new_fallback(inner: fallback::Group) -> Self {676Group {677inner: imp::Group::from(inner),678}679}680681/// Creates a new `Group` with the given delimiter and token stream.682///683/// This constructor will set the span for this group to684/// `Span::call_site()`. To change the span you can use the `set_span`685/// method below.686pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {687Group {688inner: imp::Group::new(delimiter, stream.inner),689}690}691692/// Returns the punctuation used as the delimiter for this group: a set of693/// parentheses, square brackets, or curly braces.694pub fn delimiter(&self) -> Delimiter {695self.inner.delimiter()696}697698/// Returns the `TokenStream` of tokens that are delimited in this `Group`.699///700/// Note that the returned token stream does not include the delimiter701/// returned above.702pub fn stream(&self) -> TokenStream {703TokenStream::_new(self.inner.stream())704}705706/// Returns the span for the delimiters of this token stream, spanning the707/// entire `Group`.708///709/// ```text710/// pub fn span(&self) -> Span {711/// ^^^^^^^712/// ```713pub fn span(&self) -> Span {714Span::_new(self.inner.span())715}716717/// Returns the span pointing to the opening delimiter of this group.718///719/// ```text720/// pub fn span_open(&self) -> Span {721/// ^722/// ```723pub fn span_open(&self) -> Span {724Span::_new(self.inner.span_open())725}726727/// Returns the span pointing to the closing delimiter of this group.728///729/// ```text730/// pub fn span_close(&self) -> Span {731/// ^732/// ```733pub fn span_close(&self) -> Span {734Span::_new(self.inner.span_close())735}736737/// Returns an object that holds this group's `span_open()` and738/// `span_close()` together (in a more compact representation than holding739/// those 2 spans individually).740pub fn delim_span(&self) -> DelimSpan {741DelimSpan::new(&self.inner)742}743744/// Configures the span for this `Group`'s delimiters, but not its internal745/// tokens.746///747/// This method will **not** set the span of all the internal tokens spanned748/// by this group, but rather it will only set the span of the delimiter749/// tokens at the level of the `Group`.750pub fn set_span(&mut self, span: Span) {751self.inner.set_span(span.inner);752}753}754755/// Prints the group as a string that should be losslessly convertible back756/// into the same group (modulo spans), except for possibly `TokenTree::Group`s757/// with `Delimiter::None` delimiters.758impl Display for Group {759fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {760Display::fmt(&self.inner, formatter)761}762}763764impl Debug for Group {765fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {766Debug::fmt(&self.inner, formatter)767}768}769770/// A `Punct` is a single punctuation character like `+`, `-` or `#`.771///772/// Multicharacter operators like `+=` are represented as two instances of773/// `Punct` with different forms of `Spacing` returned.774#[derive(Clone)]775pub struct Punct {776ch: char,777spacing: Spacing,778span: Span,779}780781/// Whether a `Punct` is followed immediately by another `Punct` or followed by782/// another token or whitespace.783#[derive(Copy, Clone, Debug, Eq, PartialEq)]784pub enum Spacing {785/// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.786Alone,787/// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.788///789/// Additionally, single quote `'` can join with identifiers to form790/// lifetimes `'ident`.791Joint,792}793794impl Punct {795/// Creates a new `Punct` from the given character and spacing.796///797/// The `ch` argument must be a valid punctuation character permitted by the798/// language, otherwise the function will panic.799///800/// The returned `Punct` will have the default span of `Span::call_site()`801/// which can be further configured with the `set_span` method below.802pub fn new(ch: char, spacing: Spacing) -> Self {803if let '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';'804| '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch805{806Punct {807ch,808spacing,809span: Span::call_site(),810}811} else {812panic!("unsupported proc macro punctuation character {:?}", ch);813}814}815816/// Returns the value of this punctuation character as `char`.817pub fn as_char(&self) -> char {818self.ch819}820821/// Returns the spacing of this punctuation character, indicating whether822/// it's immediately followed by another `Punct` in the token stream, so823/// they can potentially be combined into a multicharacter operator824/// (`Joint`), or it's followed by some other token or whitespace (`Alone`)825/// so the operator has certainly ended.826pub fn spacing(&self) -> Spacing {827self.spacing828}829830/// Returns the span for this punctuation character.831pub fn span(&self) -> Span {832self.span833}834835/// Configure the span for this punctuation character.836pub fn set_span(&mut self, span: Span) {837self.span = span;838}839}840841/// Prints the punctuation character as a string that should be losslessly842/// convertible back into the same character.843impl Display for Punct {844fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {845Display::fmt(&self.ch, f)846}847}848849impl Debug for Punct {850fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {851let mut debug = fmt.debug_struct("Punct");852debug.field("char", &self.ch);853debug.field("spacing", &self.spacing);854imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);855debug.finish()856}857}858859/// A word of Rust code, which may be a keyword or legal variable name.860///861/// An identifier consists of at least one Unicode code point, the first of862/// which has the XID_Start property and the rest of which have the XID_Continue863/// property.864///865/// - The empty string is not an identifier. Use `Option<Ident>`.866/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.867///868/// An identifier constructed with `Ident::new` is permitted to be a Rust869/// keyword, though parsing one through its [`Parse`] implementation rejects870/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the871/// behaviour of `Ident::new`.872///873/// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html874///875/// # Examples876///877/// A new ident can be created from a string using the `Ident::new` function.878/// A span must be provided explicitly which governs the name resolution879/// behavior of the resulting identifier.880///881/// ```882/// use proc_macro2::{Ident, Span};883///884/// fn main() {885/// let call_ident = Ident::new("calligraphy", Span::call_site());886///887/// println!("{}", call_ident);888/// }889/// ```890///891/// An ident can be interpolated into a token stream using the `quote!` macro.892///893/// ```894/// use proc_macro2::{Ident, Span};895/// use quote::quote;896///897/// fn main() {898/// let ident = Ident::new("demo", Span::call_site());899///900/// // Create a variable binding whose name is this ident.901/// let expanded = quote! { let #ident = 10; };902///903/// // Create a variable binding with a slightly different name.904/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());905/// let expanded = quote! { let #temp_ident = 10; };906/// }907/// ```908///909/// A string representation of the ident is available through the `to_string()`910/// method.911///912/// ```913/// # use proc_macro2::{Ident, Span};914/// #915/// # let ident = Ident::new("another_identifier", Span::call_site());916/// #917/// // Examine the ident as a string.918/// let ident_string = ident.to_string();919/// if ident_string.len() > 60 {920/// println!("Very long identifier: {}", ident_string)921/// }922/// ```923#[derive(Clone)]924pub struct Ident {925inner: imp::Ident,926_marker: ProcMacroAutoTraits,927}928929impl Ident {930fn _new(inner: imp::Ident) -> Self {931Ident {932inner,933_marker: MARKER,934}935}936937fn _new_fallback(inner: fallback::Ident) -> Self {938Ident {939inner: imp::Ident::from(inner),940_marker: MARKER,941}942}943944/// Creates a new `Ident` with the given `string` as well as the specified945/// `span`.946///947/// The `string` argument must be a valid identifier permitted by the948/// language, otherwise the function will panic.949///950/// Note that `span`, currently in rustc, configures the hygiene information951/// for this identifier.952///953/// As of this time `Span::call_site()` explicitly opts-in to "call-site"954/// hygiene meaning that identifiers created with this span will be resolved955/// as if they were written directly at the location of the macro call, and956/// other code at the macro call site will be able to refer to them as well.957///958/// Later spans like `Span::def_site()` will allow to opt-in to959/// "definition-site" hygiene meaning that identifiers created with this960/// span will be resolved at the location of the macro definition and other961/// code at the macro call site will not be able to refer to them.962///963/// Due to the current importance of hygiene this constructor, unlike other964/// tokens, requires a `Span` to be specified at construction.965///966/// # Panics967///968/// Panics if the input string is neither a keyword nor a legal variable969/// name. If you are not sure whether the string contains an identifier and970/// need to handle an error case, use971/// <a href="https://docs.rs/syn/2.0/syn/fn.parse_str.html"><code972/// style="padding-right:0;">syn::parse_str</code></a><code973/// style="padding-left:0;">::<Ident></code>974/// rather than `Ident::new`.975#[track_caller]976pub fn new(string: &str, span: Span) -> Self {977Ident::_new(imp::Ident::new_checked(string, span.inner))978}979980/// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The981/// `string` argument must be a valid identifier permitted by the language982/// (including keywords, e.g. `fn`). Keywords which are usable in path983/// segments (e.g. `self`, `super`) are not supported, and will cause a984/// panic.985#[track_caller]986pub fn new_raw(string: &str, span: Span) -> Self {987Ident::_new(imp::Ident::new_raw_checked(string, span.inner))988}989990/// Returns the span of this `Ident`.991pub fn span(&self) -> Span {992Span::_new(self.inner.span())993}994995/// Configures the span of this `Ident`, possibly changing its hygiene996/// context.997pub fn set_span(&mut self, span: Span) {998self.inner.set_span(span.inner);999}1000}10011002impl PartialEq for Ident {1003fn eq(&self, other: &Ident) -> bool {1004self.inner == other.inner1005}1006}10071008impl<T> PartialEq<T> for Ident1009where1010T: ?Sized + AsRef<str>,1011{1012fn eq(&self, other: &T) -> bool {1013self.inner == other1014}1015}10161017impl Eq for Ident {}10181019impl PartialOrd for Ident {1020fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {1021Some(self.cmp(other))1022}1023}10241025impl Ord for Ident {1026fn cmp(&self, other: &Ident) -> Ordering {1027self.to_string().cmp(&other.to_string())1028}1029}10301031impl Hash for Ident {1032fn hash<H: Hasher>(&self, hasher: &mut H) {1033self.to_string().hash(hasher);1034}1035}10361037/// Prints the identifier as a string that should be losslessly convertible back1038/// into the same identifier.1039impl Display for Ident {1040fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {1041Display::fmt(&self.inner, f)1042}1043}10441045impl Debug for Ident {1046fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {1047Debug::fmt(&self.inner, f)1048}1049}10501051/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),1052/// byte character (`b'a'`), an integer or floating point number with or without1053/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).1054///1055/// Boolean literals like `true` and `false` do not belong here, they are1056/// `Ident`s.1057#[derive(Clone)]1058pub struct Literal {1059inner: imp::Literal,1060_marker: ProcMacroAutoTraits,1061}10621063macro_rules! suffixed_int_literals {1064($($name:ident => $kind:ident,)*) => ($(1065/// Creates a new suffixed integer literal with the specified value.1066///1067/// This function will create an integer like `1u32` where the integer1068/// value specified is the first part of the token and the integral is1069/// also suffixed at the end. Literals created from negative numbers may1070/// not survive roundtrips through `TokenStream` or strings and may be1071/// broken into two tokens (`-` and positive literal).1072///1073/// Literals created through this method have the `Span::call_site()`1074/// span by default, which can be configured with the `set_span` method1075/// below.1076pub fn $name(n: $kind) -> Literal {1077Literal::_new(imp::Literal::$name(n))1078}1079)*)1080}10811082macro_rules! unsuffixed_int_literals {1083($($name:ident => $kind:ident,)*) => ($(1084/// Creates a new unsuffixed integer literal with the specified value.1085///1086/// This function will create an integer like `1` where the integer1087/// value specified is the first part of the token. No suffix is1088/// specified on this token, meaning that invocations like1089/// `Literal::i8_unsuffixed(1)` are equivalent to1090/// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers1091/// may not survive roundtrips through `TokenStream` or strings and may1092/// be broken into two tokens (`-` and positive literal).1093///1094/// Literals created through this method have the `Span::call_site()`1095/// span by default, which can be configured with the `set_span` method1096/// below.1097pub fn $name(n: $kind) -> Literal {1098Literal::_new(imp::Literal::$name(n))1099}1100)*)1101}11021103impl Literal {1104fn _new(inner: imp::Literal) -> Self {1105Literal {1106inner,1107_marker: MARKER,1108}1109}11101111fn _new_fallback(inner: fallback::Literal) -> Self {1112Literal {1113inner: imp::Literal::from(inner),1114_marker: MARKER,1115}1116}11171118suffixed_int_literals! {1119u8_suffixed => u8,1120u16_suffixed => u16,1121u32_suffixed => u32,1122u64_suffixed => u64,1123u128_suffixed => u128,1124usize_suffixed => usize,1125i8_suffixed => i8,1126i16_suffixed => i16,1127i32_suffixed => i32,1128i64_suffixed => i64,1129i128_suffixed => i128,1130isize_suffixed => isize,1131}11321133unsuffixed_int_literals! {1134u8_unsuffixed => u8,1135u16_unsuffixed => u16,1136u32_unsuffixed => u32,1137u64_unsuffixed => u64,1138u128_unsuffixed => u128,1139usize_unsuffixed => usize,1140i8_unsuffixed => i8,1141i16_unsuffixed => i16,1142i32_unsuffixed => i32,1143i64_unsuffixed => i64,1144i128_unsuffixed => i128,1145isize_unsuffixed => isize,1146}11471148/// Creates a new unsuffixed floating-point literal.1149///1150/// This constructor is similar to those like `Literal::i8_unsuffixed` where1151/// the float's value is emitted directly into the token but no suffix is1152/// used, so it may be inferred to be a `f64` later in the compiler.1153/// Literals created from negative numbers may not survive round-trips1154/// through `TokenStream` or strings and may be broken into two tokens (`-`1155/// and positive literal).1156///1157/// # Panics1158///1159/// This function requires that the specified float is finite, for example1160/// if it is infinity or NaN this function will panic.1161pub fn f64_unsuffixed(f: f64) -> Literal {1162assert!(f.is_finite());1163Literal::_new(imp::Literal::f64_unsuffixed(f))1164}11651166/// Creates a new suffixed floating-point literal.1167///1168/// This constructor will create a literal like `1.0f64` where the value1169/// specified is the preceding part of the token and `f64` is the suffix of1170/// the token. This token will always be inferred to be an `f64` in the1171/// compiler. Literals created from negative numbers may not survive1172/// round-trips through `TokenStream` or strings and may be broken into two1173/// tokens (`-` and positive literal).1174///1175/// # Panics1176///1177/// This function requires that the specified float is finite, for example1178/// if it is infinity or NaN this function will panic.1179pub fn f64_suffixed(f: f64) -> Literal {1180assert!(f.is_finite());1181Literal::_new(imp::Literal::f64_suffixed(f))1182}11831184/// Creates a new unsuffixed floating-point literal.1185///1186/// This constructor is similar to those like `Literal::i8_unsuffixed` where1187/// the float's value is emitted directly into the token but no suffix is1188/// used, so it may be inferred to be a `f64` later in the compiler.1189/// Literals created from negative numbers may not survive round-trips1190/// through `TokenStream` or strings and may be broken into two tokens (`-`1191/// and positive literal).1192///1193/// # Panics1194///1195/// This function requires that the specified float is finite, for example1196/// if it is infinity or NaN this function will panic.1197pub fn f32_unsuffixed(f: f32) -> Literal {1198assert!(f.is_finite());1199Literal::_new(imp::Literal::f32_unsuffixed(f))1200}12011202/// Creates a new suffixed floating-point literal.1203///1204/// This constructor will create a literal like `1.0f32` where the value1205/// specified is the preceding part of the token and `f32` is the suffix of1206/// the token. This token will always be inferred to be an `f32` in the1207/// compiler. Literals created from negative numbers may not survive1208/// round-trips through `TokenStream` or strings and may be broken into two1209/// tokens (`-` and positive literal).1210///1211/// # Panics1212///1213/// This function requires that the specified float is finite, for example1214/// if it is infinity or NaN this function will panic.1215pub fn f32_suffixed(f: f32) -> Literal {1216assert!(f.is_finite());1217Literal::_new(imp::Literal::f32_suffixed(f))1218}12191220/// String literal.1221pub fn string(string: &str) -> Literal {1222Literal::_new(imp::Literal::string(string))1223}12241225/// Character literal.1226pub fn character(ch: char) -> Literal {1227Literal::_new(imp::Literal::character(ch))1228}12291230/// Byte character literal.1231pub fn byte_character(byte: u8) -> Literal {1232Literal::_new(imp::Literal::byte_character(byte))1233}12341235/// Byte string literal.1236pub fn byte_string(bytes: &[u8]) -> Literal {1237Literal::_new(imp::Literal::byte_string(bytes))1238}12391240/// C string literal.1241pub fn c_string(string: &CStr) -> Literal {1242Literal::_new(imp::Literal::c_string(string))1243}12441245/// Returns the span encompassing this literal.1246pub fn span(&self) -> Span {1247Span::_new(self.inner.span())1248}12491250/// Configures the span associated for this literal.1251pub fn set_span(&mut self, span: Span) {1252self.inner.set_span(span.inner);1253}12541255/// Returns a `Span` that is a subset of `self.span()` containing only1256/// the source bytes in range `range`. Returns `None` if the would-be1257/// trimmed span is outside the bounds of `self`.1258///1259/// Warning: the underlying [`proc_macro::Literal::subspan`] method is1260/// nightly-only. When called from within a procedural macro not using a1261/// nightly compiler, this method will always return `None`.1262pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {1263self.inner.subspan(range).map(Span::_new)1264}12651266// Intended for the `quote!` macro to use when constructing a proc-macro21267// token out of a macro_rules $:literal token, which is already known to be1268// a valid literal. This avoids reparsing/validating the literal's string1269// representation. This is not public API other than for quote.1270#[doc(hidden)]1271pub unsafe fn from_str_unchecked(repr: &str) -> Self {1272Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })1273}1274}12751276impl FromStr for Literal {1277type Err = LexError;12781279fn from_str(repr: &str) -> Result<Self, LexError> {1280match imp::Literal::from_str_checked(repr) {1281Ok(lit) => Ok(Literal::_new(lit)),1282Err(lex) => Err(LexError {1283inner: lex,1284_marker: MARKER,1285}),1286}1287}1288}12891290impl Debug for Literal {1291fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {1292Debug::fmt(&self.inner, f)1293}1294}12951296impl Display for Literal {1297fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {1298Display::fmt(&self.inner, f)1299}1300}13011302/// Public implementation details for the `TokenStream` type, such as iterators.1303pub mod token_stream {1304use crate::marker::{ProcMacroAutoTraits, MARKER};1305use crate::{imp, TokenTree};1306use core::fmt::{self, Debug};13071308pub use crate::TokenStream;13091310/// An iterator over `TokenStream`'s `TokenTree`s.1311///1312/// The iteration is "shallow", e.g. the iterator doesn't recurse into1313/// delimited groups, and returns whole groups as token trees.1314#[derive(Clone)]1315pub struct IntoIter {1316inner: imp::TokenTreeIter,1317_marker: ProcMacroAutoTraits,1318}13191320impl Iterator for IntoIter {1321type Item = TokenTree;13221323fn next(&mut self) -> Option<TokenTree> {1324self.inner.next()1325}13261327fn size_hint(&self) -> (usize, Option<usize>) {1328self.inner.size_hint()1329}1330}13311332impl Debug for IntoIter {1333fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {1334f.write_str("TokenStream ")?;1335f.debug_list().entries(self.clone()).finish()1336}1337}13381339impl IntoIterator for TokenStream {1340type Item = TokenTree;1341type IntoIter = IntoIter;13421343fn into_iter(self) -> IntoIter {1344IntoIter {1345inner: self.inner.into_iter(),1346_marker: MARKER,1347}1348}1349}1350}135113521353