// SPDX-License-Identifier: Apache-2.0 OR MIT12// When fixdep scans this, it will find this string `CONFIG_RUSTC_VERSION_TEXT`3// and thus add a dependency on `include/config/RUSTC_VERSION_TEXT`, which is4// touched by Kconfig when the version string from the compiler changes.56//! [![github]](https://github.com/dtolnay/proc-macro2) [![crates-io]](https://crates.io/crates/proc-macro2) [![docs-rs]](crate)7//!8//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github9//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust10//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs11//!12//! <br>13//!14//! A wrapper around the procedural macro API of the compiler's [`proc_macro`]15//! crate. This library serves two purposes:16//!17//! - **Bring proc-macro-like functionality to other contexts like build.rs and18//! main.rs.** Types from `proc_macro` are entirely specific to procedural19//! macros and cannot ever exist in code outside of a procedural macro.20//! Meanwhile `proc_macro2` types may exist anywhere including non-macro code.21//! By developing foundational libraries like [syn] and [quote] against22//! `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem23//! becomes easily applicable to many other use cases and we avoid24//! reimplementing non-macro equivalents of those libraries.25//!26//! - **Make procedural macros unit testable.** As a consequence of being27//! specific to procedural macros, nothing that uses `proc_macro` can be28//! executed from a unit test. In order for helper libraries or components of29//! a macro to be testable in isolation, they must be implemented using30//! `proc_macro2`.31//!32//! [syn]: https://github.com/dtolnay/syn33//! [quote]: https://github.com/dtolnay/quote34//!35//! # Usage36//!37//! The skeleton of a typical procedural macro typically looks like this:38//!39//! ```40//! extern crate proc_macro;41//!42//! # const IGNORE: &str = stringify! {43//! #[proc_macro_derive(MyDerive)]44//! # };45//! # #[cfg(wrap_proc_macro)]46//! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {47//! let input = proc_macro2::TokenStream::from(input);48//!49//! let output: proc_macro2::TokenStream = {50//! /* transform input */51//! # input52//! };53//!54//! proc_macro::TokenStream::from(output)55//! }56//! ```57//!58//! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to59//! propagate parse errors correctly back to the compiler when parsing fails.60//!61//! [`parse_macro_input!`]: https://docs.rs/syn/2.0/syn/macro.parse_macro_input.html62//!63//! # Unstable features64//!65//! The default feature set of proc-macro2 tracks the most recent stable66//! compiler API. Functionality in `proc_macro` that is not yet stable is not67//! exposed by proc-macro2 by default.68//!69//! To opt into the additional APIs available in the most recent nightly70//! compiler, the `procmacro2_semver_exempt` config flag must be passed to71//! rustc. We will polyfill those nightly-only APIs back to Rust 1.56.0. As72//! these are unstable APIs that track the nightly compiler, minor versions of73//! proc-macro2 may make breaking changes to them at any time.74//!75//! ```sh76//! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build77//! ```78//!79//! Note that this must not only be done for your crate, but for any crate that80//! depends on your crate. This infectious nature is intentional, as it serves81//! as a reminder that you are outside of the normal semver guarantees.82//!83//! Semver exempt methods are marked as such in the proc-macro2 documentation.84//!85//! # Thread-Safety86//!87//! Most types in this crate are `!Sync` because the underlying compiler88//! types make use of thread-local memory, meaning they cannot be accessed from89//! a different thread.9091// Proc-macro2 types in rustdoc of other crates get linked to here.92#![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.101")]93#![cfg_attr(any(proc_macro_span, super_unstable), feature(proc_macro_span))]94#![cfg_attr(super_unstable, feature(proc_macro_def_site))]95#![cfg_attr(docsrs, feature(doc_cfg))]96#![deny(unsafe_op_in_unsafe_fn)]97#![allow(98clippy::cast_lossless,99clippy::cast_possible_truncation,100clippy::checked_conversions,101clippy::doc_markdown,102clippy::elidable_lifetime_names,103clippy::incompatible_msrv,104clippy::items_after_statements,105clippy::iter_without_into_iter,106clippy::let_underscore_untyped,107clippy::manual_assert,108clippy::manual_range_contains,109clippy::missing_panics_doc,110clippy::missing_safety_doc,111clippy::must_use_candidate,112clippy::needless_doctest_main,113clippy::needless_lifetimes,114clippy::new_without_default,115clippy::return_self_not_must_use,116clippy::shadow_unrelated,117clippy::trivially_copy_pass_by_ref,118clippy::unnecessary_wraps,119clippy::unused_self,120clippy::used_underscore_binding,121clippy::vec_init_then_push122)]123#![allow(unknown_lints, mismatched_lifetime_syntaxes)]124125#[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))]126compile_error! {"\127Something is not right. If you've tried to turn on \128procmacro2_semver_exempt, you need to ensure that it \129is turned on for the compilation of the proc-macro2 \130build script as well.131"}132133#[cfg(all(134procmacro2_nightly_testing,135feature = "proc-macro",136not(proc_macro_span)137))]138compile_error! {"\139Build script probe failed to compile.140"}141142extern crate alloc;143144#[cfg(feature = "proc-macro")]145extern crate proc_macro;146147mod marker;148mod parse;149mod probe;150mod rcvec;151152#[cfg(wrap_proc_macro)]153mod detection;154155// Public for proc_macro2::fallback::force() and unforce(), but those are quite156// a niche use case so we omit it from rustdoc.157#[doc(hidden)]158pub mod fallback;159160pub mod extra;161162#[cfg(not(wrap_proc_macro))]163use crate::fallback as imp;164#[path = "wrapper.rs"]165#[cfg(wrap_proc_macro)]166mod imp;167168#[cfg(span_locations)]169mod location;170171use crate::extra::DelimSpan;172use crate::marker::{ProcMacroAutoTraits, MARKER};173use core::cmp::Ordering;174use core::fmt::{self, Debug, Display};175use core::hash::{Hash, Hasher};176#[cfg(span_locations)]177use core::ops::Range;178use core::ops::RangeBounds;179use core::str::FromStr;180use std::error::Error;181use std::ffi::CStr;182#[cfg(span_locations)]183use std::path::PathBuf;184185#[cfg(span_locations)]186#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]187pub use crate::location::LineColumn;188189/// An abstract stream of tokens, or more concretely a sequence of token trees.190///191/// This type provides interfaces for iterating over token trees and for192/// collecting token trees into one stream.193///194/// Token stream is both the input and output of `#[proc_macro]`,195/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.196#[derive(Clone)]197pub struct TokenStream {198inner: imp::TokenStream,199_marker: ProcMacroAutoTraits,200}201202/// Error returned from `TokenStream::from_str`.203pub struct LexError {204inner: imp::LexError,205_marker: ProcMacroAutoTraits,206}207208impl TokenStream {209fn _new(inner: imp::TokenStream) -> Self {210TokenStream {211inner,212_marker: MARKER,213}214}215216fn _new_fallback(inner: fallback::TokenStream) -> Self {217TokenStream {218inner: imp::TokenStream::from(inner),219_marker: MARKER,220}221}222223/// Returns an empty `TokenStream` containing no token trees.224pub fn new() -> Self {225TokenStream::_new(imp::TokenStream::new())226}227228/// Checks if this `TokenStream` is empty.229pub fn is_empty(&self) -> bool {230self.inner.is_empty()231}232}233234/// `TokenStream::default()` returns an empty stream,235/// i.e. this is equivalent with `TokenStream::new()`.236impl Default for TokenStream {237fn default() -> Self {238TokenStream::new()239}240}241242/// Attempts to break the string into tokens and parse those tokens into a token243/// stream.244///245/// May fail for a number of reasons, for example, if the string contains246/// unbalanced delimiters or characters not existing in the language.247///248/// NOTE: Some errors may cause panics instead of returning `LexError`. We249/// reserve the right to change these errors into `LexError`s later.250impl FromStr for TokenStream {251type Err = LexError;252253fn from_str(src: &str) -> Result<TokenStream, LexError> {254match imp::TokenStream::from_str_checked(src) {255Ok(tokens) => Ok(TokenStream::_new(tokens)),256Err(lex) => Err(LexError {257inner: lex,258_marker: MARKER,259}),260}261}262}263264#[cfg(feature = "proc-macro")]265#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]266impl From<proc_macro::TokenStream> for TokenStream {267fn from(inner: proc_macro::TokenStream) -> Self {268TokenStream::_new(imp::TokenStream::from(inner))269}270}271272#[cfg(feature = "proc-macro")]273#[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]274impl From<TokenStream> for proc_macro::TokenStream {275fn from(inner: TokenStream) -> Self {276proc_macro::TokenStream::from(inner.inner)277}278}279280impl From<TokenTree> for TokenStream {281fn from(token: TokenTree) -> Self {282TokenStream::_new(imp::TokenStream::from(token))283}284}285286impl Extend<TokenTree> for TokenStream {287fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {288self.inner.extend(streams);289}290}291292impl Extend<TokenStream> for TokenStream {293fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {294self.inner295.extend(streams.into_iter().map(|stream| stream.inner));296}297}298299/// Collects a number of token trees into a single stream.300impl FromIterator<TokenTree> for TokenStream {301fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {302TokenStream::_new(streams.into_iter().collect())303}304}305impl FromIterator<TokenStream> for TokenStream {306fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {307TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())308}309}310311/// Prints the token stream as a string that is supposed to be losslessly312/// convertible back into the same token stream (modulo spans), except for313/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative314/// numeric literals.315impl Display for TokenStream {316fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {317Display::fmt(&self.inner, f)318}319}320321/// Prints token in a form convenient for debugging.322impl Debug for TokenStream {323fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {324Debug::fmt(&self.inner, f)325}326}327328impl LexError {329pub fn span(&self) -> Span {330Span::_new(self.inner.span())331}332}333334impl Debug for LexError {335fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {336Debug::fmt(&self.inner, f)337}338}339340impl Display for LexError {341fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {342Display::fmt(&self.inner, f)343}344}345346impl Error for LexError {}347348/// A region of source code, along with macro expansion information.349#[derive(Copy, Clone)]350pub struct Span {351inner: imp::Span,352_marker: ProcMacroAutoTraits,353}354355impl Span {356fn _new(inner: imp::Span) -> Self {357Span {358inner,359_marker: MARKER,360}361}362363fn _new_fallback(inner: fallback::Span) -> Self {364Span {365inner: imp::Span::from(inner),366_marker: MARKER,367}368}369370/// The span of the invocation of the current procedural macro.371///372/// Identifiers created with this span will be resolved as if they were373/// written directly at the macro call location (call-site hygiene) and374/// other code at the macro call site will be able to refer to them as well.375pub fn call_site() -> Self {376Span::_new(imp::Span::call_site())377}378379/// The span located at the invocation of the procedural macro, but with380/// local variables, labels, and `$crate` resolved at the definition site381/// of the macro. This is the same hygiene behavior as `macro_rules`.382pub fn mixed_site() -> Self {383Span::_new(imp::Span::mixed_site())384}385386/// A span that resolves at the macro definition site.387///388/// This method is semver exempt and not exposed by default.389#[cfg(procmacro2_semver_exempt)]390#[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]391pub fn def_site() -> Self {392Span::_new(imp::Span::def_site())393}394395/// Creates a new span with the same line/column information as `self` but396/// that resolves symbols as though it were at `other`.397pub fn resolved_at(&self, other: Span) -> Span {398Span::_new(self.inner.resolved_at(other.inner))399}400401/// Creates a new span with the same name resolution behavior as `self` but402/// with the line/column information of `other`.403pub fn located_at(&self, other: Span) -> Span {404Span::_new(self.inner.located_at(other.inner))405}406407/// Convert `proc_macro2::Span` to `proc_macro::Span`.408///409/// This method is available when building with a nightly compiler, or when410/// building with rustc 1.29+ *without* semver exempt features.411///412/// # Panics413///414/// Panics if called from outside of a procedural macro. Unlike415/// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within416/// the context of a procedural macro invocation.417#[cfg(wrap_proc_macro)]418pub fn unwrap(self) -> proc_macro::Span {419self.inner.unwrap()420}421422// Soft deprecated. Please use Span::unwrap.423#[cfg(wrap_proc_macro)]424#[doc(hidden)]425pub fn unstable(self) -> proc_macro::Span {426self.unwrap()427}428429/// Returns the span's byte position range in the source file.430///431/// This method requires the `"span-locations"` feature to be enabled.432///433/// When executing in a procedural macro context, the returned range is only434/// accurate if compiled with a nightly toolchain. The stable toolchain does435/// not have this information available. When executing outside of a436/// procedural macro, such as main.rs or build.rs, the byte range is always437/// accurate regardless of toolchain.438#[cfg(span_locations)]439#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]440pub fn byte_range(&self) -> Range<usize> {441self.inner.byte_range()442}443444/// Get the starting line/column in the source file for this span.445///446/// This method requires the `"span-locations"` feature to be enabled.447///448/// When executing in a procedural macro context, the returned line/column449/// are only meaningful if compiled with a nightly toolchain. The stable450/// toolchain does not have this information available. When executing451/// outside of a procedural macro, such as main.rs or build.rs, the452/// line/column are always meaningful regardless of toolchain.453#[cfg(span_locations)]454#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]455pub fn start(&self) -> LineColumn {456self.inner.start()457}458459/// Get the ending line/column in the source file for this span.460///461/// This method requires the `"span-locations"` feature to be enabled.462///463/// When executing in a procedural macro context, the returned line/column464/// are only meaningful if compiled with a nightly toolchain. The stable465/// toolchain does not have this information available. When executing466/// outside of a procedural macro, such as main.rs or build.rs, the467/// line/column are always meaningful regardless of toolchain.468#[cfg(span_locations)]469#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]470pub fn end(&self) -> LineColumn {471self.inner.end()472}473474/// The path to the source file in which this span occurs, for display475/// purposes.476///477/// This might not correspond to a valid file system path. It might be478/// remapped, or might be an artificial path such as `"<macro expansion>"`.479#[cfg(span_locations)]480#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]481pub fn file(&self) -> String {482self.inner.file()483}484485/// The path to the source file in which this span occurs on disk.486///487/// This is the actual path on disk. It is unaffected by path remapping.488///489/// This path should not be embedded in the output of the macro; prefer490/// `file()` instead.491#[cfg(span_locations)]492#[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))]493pub fn local_file(&self) -> Option<PathBuf> {494self.inner.local_file()495}496497/// Create a new span encompassing `self` and `other`.498///499/// Returns `None` if `self` and `other` are from different files.500///501/// Warning: the underlying [`proc_macro::Span::join`] method is502/// nightly-only. When called from within a procedural macro not using a503/// nightly compiler, this method will always return `None`.504pub fn join(&self, other: Span) -> Option<Span> {505self.inner.join(other.inner).map(Span::_new)506}507508/// Compares two spans to see if they're equal.509///510/// This method is semver exempt and not exposed by default.511#[cfg(procmacro2_semver_exempt)]512#[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))]513pub fn eq(&self, other: &Span) -> bool {514self.inner.eq(&other.inner)515}516517/// Returns the source text behind a span. This preserves the original518/// source code, including spaces and comments. It only returns a result if519/// the span corresponds to real source code.520///521/// Note: The observable result of a macro should only rely on the tokens522/// and not on this source text. The result of this function is a best523/// effort to be used for diagnostics only.524pub fn source_text(&self) -> Option<String> {525self.inner.source_text()526}527}528529/// Prints a span in a form convenient for debugging.530impl Debug for Span {531fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {532Debug::fmt(&self.inner, f)533}534}535536/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).537#[derive(Clone)]538pub enum TokenTree {539/// A token stream surrounded by bracket delimiters.540Group(Group),541/// An identifier.542Ident(Ident),543/// A single punctuation character (`+`, `,`, `$`, etc.).544Punct(Punct),545/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.546Literal(Literal),547}548549impl TokenTree {550/// Returns the span of this tree, delegating to the `span` method of551/// the contained token or a delimited stream.552pub fn span(&self) -> Span {553match self {554TokenTree::Group(t) => t.span(),555TokenTree::Ident(t) => t.span(),556TokenTree::Punct(t) => t.span(),557TokenTree::Literal(t) => t.span(),558}559}560561/// Configures the span for *only this token*.562///563/// Note that if this token is a `Group` then this method will not configure564/// the span of each of the internal tokens, this will simply delegate to565/// the `set_span` method of each variant.566pub fn set_span(&mut self, span: Span) {567match self {568TokenTree::Group(t) => t.set_span(span),569TokenTree::Ident(t) => t.set_span(span),570TokenTree::Punct(t) => t.set_span(span),571TokenTree::Literal(t) => t.set_span(span),572}573}574}575576impl From<Group> for TokenTree {577fn from(g: Group) -> Self {578TokenTree::Group(g)579}580}581582impl From<Ident> for TokenTree {583fn from(g: Ident) -> Self {584TokenTree::Ident(g)585}586}587588impl From<Punct> for TokenTree {589fn from(g: Punct) -> Self {590TokenTree::Punct(g)591}592}593594impl From<Literal> for TokenTree {595fn from(g: Literal) -> Self {596TokenTree::Literal(g)597}598}599600/// Prints the token tree as a string that is supposed to be losslessly601/// convertible back into the same token tree (modulo spans), except for602/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative603/// numeric literals.604impl Display for TokenTree {605fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {606match self {607TokenTree::Group(t) => Display::fmt(t, f),608TokenTree::Ident(t) => Display::fmt(t, f),609TokenTree::Punct(t) => Display::fmt(t, f),610TokenTree::Literal(t) => Display::fmt(t, f),611}612}613}614615/// Prints token tree in a form convenient for debugging.616impl Debug for TokenTree {617fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {618// Each of these has the name in the struct type in the derived debug,619// so don't bother with an extra layer of indirection620match self {621TokenTree::Group(t) => Debug::fmt(t, f),622TokenTree::Ident(t) => {623let mut debug = f.debug_struct("Ident");624debug.field("sym", &format_args!("{}", t));625imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);626debug.finish()627}628TokenTree::Punct(t) => Debug::fmt(t, f),629TokenTree::Literal(t) => Debug::fmt(t, f),630}631}632}633634/// A delimited token stream.635///636/// A `Group` internally contains a `TokenStream` which is surrounded by637/// `Delimiter`s.638#[derive(Clone)]639pub struct Group {640inner: imp::Group,641}642643/// Describes how a sequence of token trees is delimited.644#[derive(Copy, Clone, Debug, Eq, PartialEq)]645pub enum Delimiter {646/// `( ... )`647Parenthesis,648/// `{ ... }`649Brace,650/// `[ ... ]`651Bracket,652/// `∅ ... ∅`653///654/// An invisible delimiter, that may, for example, appear around tokens655/// coming from a "macro variable" `$var`. It is important to preserve656/// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.657/// Invisible delimiters may not survive roundtrip of a token stream through658/// a string.659///660/// <div class="warning">661///662/// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output663/// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input664/// of a proc_macro macro are preserved, and only in very specific circumstances.665/// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve666/// operator priorities as indicated above. The other `Delimiter` variants should be used667/// instead in this context. This is a rustc bug. For details, see668/// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).669///670/// </div>671None,672}673674impl Group {675fn _new(inner: imp::Group) -> Self {676Group { inner }677}678679fn _new_fallback(inner: fallback::Group) -> Self {680Group {681inner: imp::Group::from(inner),682}683}684685/// Creates a new `Group` with the given delimiter and token stream.686///687/// This constructor will set the span for this group to688/// `Span::call_site()`. To change the span you can use the `set_span`689/// method below.690pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {691Group {692inner: imp::Group::new(delimiter, stream.inner),693}694}695696/// Returns the punctuation used as the delimiter for this group: a set of697/// parentheses, square brackets, or curly braces.698pub fn delimiter(&self) -> Delimiter {699self.inner.delimiter()700}701702/// Returns the `TokenStream` of tokens that are delimited in this `Group`.703///704/// Note that the returned token stream does not include the delimiter705/// returned above.706pub fn stream(&self) -> TokenStream {707TokenStream::_new(self.inner.stream())708}709710/// Returns the span for the delimiters of this token stream, spanning the711/// entire `Group`.712///713/// ```text714/// pub fn span(&self) -> Span {715/// ^^^^^^^716/// ```717pub fn span(&self) -> Span {718Span::_new(self.inner.span())719}720721/// Returns the span pointing to the opening delimiter of this group.722///723/// ```text724/// pub fn span_open(&self) -> Span {725/// ^726/// ```727pub fn span_open(&self) -> Span {728Span::_new(self.inner.span_open())729}730731/// Returns the span pointing to the closing delimiter of this group.732///733/// ```text734/// pub fn span_close(&self) -> Span {735/// ^736/// ```737pub fn span_close(&self) -> Span {738Span::_new(self.inner.span_close())739}740741/// Returns an object that holds this group's `span_open()` and742/// `span_close()` together (in a more compact representation than holding743/// those 2 spans individually).744pub fn delim_span(&self) -> DelimSpan {745DelimSpan::new(&self.inner)746}747748/// Configures the span for this `Group`'s delimiters, but not its internal749/// tokens.750///751/// This method will **not** set the span of all the internal tokens spanned752/// by this group, but rather it will only set the span of the delimiter753/// tokens at the level of the `Group`.754pub fn set_span(&mut self, span: Span) {755self.inner.set_span(span.inner);756}757}758759/// Prints the group as a string that should be losslessly convertible back760/// into the same group (modulo spans), except for possibly `TokenTree::Group`s761/// with `Delimiter::None` delimiters.762impl Display for Group {763fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {764Display::fmt(&self.inner, formatter)765}766}767768impl Debug for Group {769fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {770Debug::fmt(&self.inner, formatter)771}772}773774/// A `Punct` is a single punctuation character like `+`, `-` or `#`.775///776/// Multicharacter operators like `+=` are represented as two instances of777/// `Punct` with different forms of `Spacing` returned.778#[derive(Clone)]779pub struct Punct {780ch: char,781spacing: Spacing,782span: Span,783}784785/// Whether a `Punct` is followed immediately by another `Punct` or followed by786/// another token or whitespace.787#[derive(Copy, Clone, Debug, Eq, PartialEq)]788pub enum Spacing {789/// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.790Alone,791/// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.792///793/// Additionally, single quote `'` can join with identifiers to form794/// lifetimes `'ident`.795Joint,796}797798impl Punct {799/// Creates a new `Punct` from the given character and spacing.800///801/// The `ch` argument must be a valid punctuation character permitted by the802/// language, otherwise the function will panic.803///804/// The returned `Punct` will have the default span of `Span::call_site()`805/// which can be further configured with the `set_span` method below.806pub fn new(ch: char, spacing: Spacing) -> Self {807if let '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';'808| '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch809{810Punct {811ch,812spacing,813span: Span::call_site(),814}815} else {816panic!("unsupported proc macro punctuation character {:?}", ch);817}818}819820/// Returns the value of this punctuation character as `char`.821pub fn as_char(&self) -> char {822self.ch823}824825/// Returns the spacing of this punctuation character, indicating whether826/// it's immediately followed by another `Punct` in the token stream, so827/// they can potentially be combined into a multicharacter operator828/// (`Joint`), or it's followed by some other token or whitespace (`Alone`)829/// so the operator has certainly ended.830pub fn spacing(&self) -> Spacing {831self.spacing832}833834/// Returns the span for this punctuation character.835pub fn span(&self) -> Span {836self.span837}838839/// Configure the span for this punctuation character.840pub fn set_span(&mut self, span: Span) {841self.span = span;842}843}844845/// Prints the punctuation character as a string that should be losslessly846/// convertible back into the same character.847impl Display for Punct {848fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {849Display::fmt(&self.ch, f)850}851}852853impl Debug for Punct {854fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {855let mut debug = fmt.debug_struct("Punct");856debug.field("char", &self.ch);857debug.field("spacing", &self.spacing);858imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);859debug.finish()860}861}862863/// A word of Rust code, which may be a keyword or legal variable name.864///865/// An identifier consists of at least one Unicode code point, the first of866/// which has the XID_Start property and the rest of which have the XID_Continue867/// property.868///869/// - The empty string is not an identifier. Use `Option<Ident>`.870/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.871///872/// An identifier constructed with `Ident::new` is permitted to be a Rust873/// keyword, though parsing one through its [`Parse`] implementation rejects874/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the875/// behaviour of `Ident::new`.876///877/// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html878///879/// # Examples880///881/// A new ident can be created from a string using the `Ident::new` function.882/// A span must be provided explicitly which governs the name resolution883/// behavior of the resulting identifier.884///885/// ```886/// use proc_macro2::{Ident, Span};887///888/// fn main() {889/// let call_ident = Ident::new("calligraphy", Span::call_site());890///891/// println!("{}", call_ident);892/// }893/// ```894///895/// An ident can be interpolated into a token stream using the `quote!` macro.896///897/// ```898/// use proc_macro2::{Ident, Span};899/// use quote::quote;900///901/// fn main() {902/// let ident = Ident::new("demo", Span::call_site());903///904/// // Create a variable binding whose name is this ident.905/// let expanded = quote! { let #ident = 10; };906///907/// // Create a variable binding with a slightly different name.908/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());909/// let expanded = quote! { let #temp_ident = 10; };910/// }911/// ```912///913/// A string representation of the ident is available through the `to_string()`914/// method.915///916/// ```917/// # use proc_macro2::{Ident, Span};918/// #919/// # let ident = Ident::new("another_identifier", Span::call_site());920/// #921/// // Examine the ident as a string.922/// let ident_string = ident.to_string();923/// if ident_string.len() > 60 {924/// println!("Very long identifier: {}", ident_string)925/// }926/// ```927#[derive(Clone)]928pub struct Ident {929inner: imp::Ident,930_marker: ProcMacroAutoTraits,931}932933impl Ident {934fn _new(inner: imp::Ident) -> Self {935Ident {936inner,937_marker: MARKER,938}939}940941fn _new_fallback(inner: fallback::Ident) -> Self {942Ident {943inner: imp::Ident::from(inner),944_marker: MARKER,945}946}947948/// Creates a new `Ident` with the given `string` as well as the specified949/// `span`.950///951/// The `string` argument must be a valid identifier permitted by the952/// language, otherwise the function will panic.953///954/// Note that `span`, currently in rustc, configures the hygiene information955/// for this identifier.956///957/// As of this time `Span::call_site()` explicitly opts-in to "call-site"958/// hygiene meaning that identifiers created with this span will be resolved959/// as if they were written directly at the location of the macro call, and960/// other code at the macro call site will be able to refer to them as well.961///962/// Later spans like `Span::def_site()` will allow to opt-in to963/// "definition-site" hygiene meaning that identifiers created with this964/// span will be resolved at the location of the macro definition and other965/// code at the macro call site will not be able to refer to them.966///967/// Due to the current importance of hygiene this constructor, unlike other968/// tokens, requires a `Span` to be specified at construction.969///970/// # Panics971///972/// Panics if the input string is neither a keyword nor a legal variable973/// name. If you are not sure whether the string contains an identifier and974/// need to handle an error case, use975/// <a href="https://docs.rs/syn/2.0/syn/fn.parse_str.html"><code976/// style="padding-right:0;">syn::parse_str</code></a><code977/// style="padding-left:0;">::<Ident></code>978/// rather than `Ident::new`.979#[track_caller]980pub fn new(string: &str, span: Span) -> Self {981Ident::_new(imp::Ident::new_checked(string, span.inner))982}983984/// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The985/// `string` argument must be a valid identifier permitted by the language986/// (including keywords, e.g. `fn`). Keywords which are usable in path987/// segments (e.g. `self`, `super`) are not supported, and will cause a988/// panic.989#[track_caller]990pub fn new_raw(string: &str, span: Span) -> Self {991Ident::_new(imp::Ident::new_raw_checked(string, span.inner))992}993994/// Returns the span of this `Ident`.995pub fn span(&self) -> Span {996Span::_new(self.inner.span())997}998999/// Configures the span of this `Ident`, possibly changing its hygiene1000/// context.1001pub fn set_span(&mut self, span: Span) {1002self.inner.set_span(span.inner);1003}1004}10051006impl PartialEq for Ident {1007fn eq(&self, other: &Ident) -> bool {1008self.inner == other.inner1009}1010}10111012impl<T> PartialEq<T> for Ident1013where1014T: ?Sized + AsRef<str>,1015{1016fn eq(&self, other: &T) -> bool {1017self.inner == other1018}1019}10201021impl Eq for Ident {}10221023impl PartialOrd for Ident {1024fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {1025Some(self.cmp(other))1026}1027}10281029impl Ord for Ident {1030fn cmp(&self, other: &Ident) -> Ordering {1031self.to_string().cmp(&other.to_string())1032}1033}10341035impl Hash for Ident {1036fn hash<H: Hasher>(&self, hasher: &mut H) {1037self.to_string().hash(hasher);1038}1039}10401041/// Prints the identifier as a string that should be losslessly convertible back1042/// into the same identifier.1043impl Display for Ident {1044fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {1045Display::fmt(&self.inner, f)1046}1047}10481049impl Debug for Ident {1050fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {1051Debug::fmt(&self.inner, f)1052}1053}10541055/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),1056/// byte character (`b'a'`), an integer or floating point number with or without1057/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).1058///1059/// Boolean literals like `true` and `false` do not belong here, they are1060/// `Ident`s.1061#[derive(Clone)]1062pub struct Literal {1063inner: imp::Literal,1064_marker: ProcMacroAutoTraits,1065}10661067macro_rules! suffixed_int_literals {1068($($name:ident => $kind:ident,)*) => ($(1069/// Creates a new suffixed integer literal with the specified value.1070///1071/// This function will create an integer like `1u32` where the integer1072/// value specified is the first part of the token and the integral is1073/// also suffixed at the end. Literals created from negative numbers may1074/// not survive roundtrips through `TokenStream` or strings and may be1075/// broken into two tokens (`-` and positive literal).1076///1077/// Literals created through this method have the `Span::call_site()`1078/// span by default, which can be configured with the `set_span` method1079/// below.1080pub fn $name(n: $kind) -> Literal {1081Literal::_new(imp::Literal::$name(n))1082}1083)*)1084}10851086macro_rules! unsuffixed_int_literals {1087($($name:ident => $kind:ident,)*) => ($(1088/// Creates a new unsuffixed integer literal with the specified value.1089///1090/// This function will create an integer like `1` where the integer1091/// value specified is the first part of the token. No suffix is1092/// specified on this token, meaning that invocations like1093/// `Literal::i8_unsuffixed(1)` are equivalent to1094/// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers1095/// may not survive roundtrips through `TokenStream` or strings and may1096/// be broken into two tokens (`-` and positive literal).1097///1098/// Literals created through this method have the `Span::call_site()`1099/// span by default, which can be configured with the `set_span` method1100/// below.1101pub fn $name(n: $kind) -> Literal {1102Literal::_new(imp::Literal::$name(n))1103}1104)*)1105}11061107impl Literal {1108fn _new(inner: imp::Literal) -> Self {1109Literal {1110inner,1111_marker: MARKER,1112}1113}11141115fn _new_fallback(inner: fallback::Literal) -> Self {1116Literal {1117inner: imp::Literal::from(inner),1118_marker: MARKER,1119}1120}11211122suffixed_int_literals! {1123u8_suffixed => u8,1124u16_suffixed => u16,1125u32_suffixed => u32,1126u64_suffixed => u64,1127u128_suffixed => u128,1128usize_suffixed => usize,1129i8_suffixed => i8,1130i16_suffixed => i16,1131i32_suffixed => i32,1132i64_suffixed => i64,1133i128_suffixed => i128,1134isize_suffixed => isize,1135}11361137unsuffixed_int_literals! {1138u8_unsuffixed => u8,1139u16_unsuffixed => u16,1140u32_unsuffixed => u32,1141u64_unsuffixed => u64,1142u128_unsuffixed => u128,1143usize_unsuffixed => usize,1144i8_unsuffixed => i8,1145i16_unsuffixed => i16,1146i32_unsuffixed => i32,1147i64_unsuffixed => i64,1148i128_unsuffixed => i128,1149isize_unsuffixed => isize,1150}11511152/// Creates a new unsuffixed floating-point literal.1153///1154/// This constructor is similar to those like `Literal::i8_unsuffixed` where1155/// the float's value is emitted directly into the token but no suffix is1156/// used, so it may be inferred to be a `f64` later in the compiler.1157/// Literals created from negative numbers may not survive round-trips1158/// through `TokenStream` or strings and may be broken into two tokens (`-`1159/// and positive literal).1160///1161/// # Panics1162///1163/// This function requires that the specified float is finite, for example1164/// if it is infinity or NaN this function will panic.1165pub fn f64_unsuffixed(f: f64) -> Literal {1166assert!(f.is_finite());1167Literal::_new(imp::Literal::f64_unsuffixed(f))1168}11691170/// Creates a new suffixed floating-point literal.1171///1172/// This constructor will create a literal like `1.0f64` where the value1173/// specified is the preceding part of the token and `f64` is the suffix of1174/// the token. This token will always be inferred to be an `f64` in the1175/// compiler. Literals created from negative numbers may not survive1176/// round-trips through `TokenStream` or strings and may be broken into two1177/// tokens (`-` and positive literal).1178///1179/// # Panics1180///1181/// This function requires that the specified float is finite, for example1182/// if it is infinity or NaN this function will panic.1183pub fn f64_suffixed(f: f64) -> Literal {1184assert!(f.is_finite());1185Literal::_new(imp::Literal::f64_suffixed(f))1186}11871188/// Creates a new unsuffixed floating-point literal.1189///1190/// This constructor is similar to those like `Literal::i8_unsuffixed` where1191/// the float's value is emitted directly into the token but no suffix is1192/// used, so it may be inferred to be a `f64` later in the compiler.1193/// Literals created from negative numbers may not survive round-trips1194/// through `TokenStream` or strings and may be broken into two tokens (`-`1195/// and positive literal).1196///1197/// # Panics1198///1199/// This function requires that the specified float is finite, for example1200/// if it is infinity or NaN this function will panic.1201pub fn f32_unsuffixed(f: f32) -> Literal {1202assert!(f.is_finite());1203Literal::_new(imp::Literal::f32_unsuffixed(f))1204}12051206/// Creates a new suffixed floating-point literal.1207///1208/// This constructor will create a literal like `1.0f32` where the value1209/// specified is the preceding part of the token and `f32` is the suffix of1210/// the token. This token will always be inferred to be an `f32` in the1211/// compiler. Literals created from negative numbers may not survive1212/// round-trips through `TokenStream` or strings and may be broken into two1213/// tokens (`-` and positive literal).1214///1215/// # Panics1216///1217/// This function requires that the specified float is finite, for example1218/// if it is infinity or NaN this function will panic.1219pub fn f32_suffixed(f: f32) -> Literal {1220assert!(f.is_finite());1221Literal::_new(imp::Literal::f32_suffixed(f))1222}12231224/// String literal.1225pub fn string(string: &str) -> Literal {1226Literal::_new(imp::Literal::string(string))1227}12281229/// Character literal.1230pub fn character(ch: char) -> Literal {1231Literal::_new(imp::Literal::character(ch))1232}12331234/// Byte character literal.1235pub fn byte_character(byte: u8) -> Literal {1236Literal::_new(imp::Literal::byte_character(byte))1237}12381239/// Byte string literal.1240pub fn byte_string(bytes: &[u8]) -> Literal {1241Literal::_new(imp::Literal::byte_string(bytes))1242}12431244/// C string literal.1245pub fn c_string(string: &CStr) -> Literal {1246Literal::_new(imp::Literal::c_string(string))1247}12481249/// Returns the span encompassing this literal.1250pub fn span(&self) -> Span {1251Span::_new(self.inner.span())1252}12531254/// Configures the span associated for this literal.1255pub fn set_span(&mut self, span: Span) {1256self.inner.set_span(span.inner);1257}12581259/// Returns a `Span` that is a subset of `self.span()` containing only1260/// the source bytes in range `range`. Returns `None` if the would-be1261/// trimmed span is outside the bounds of `self`.1262///1263/// Warning: the underlying [`proc_macro::Literal::subspan`] method is1264/// nightly-only. When called from within a procedural macro not using a1265/// nightly compiler, this method will always return `None`.1266pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {1267self.inner.subspan(range).map(Span::_new)1268}12691270// Intended for the `quote!` macro to use when constructing a proc-macro21271// token out of a macro_rules $:literal token, which is already known to be1272// a valid literal. This avoids reparsing/validating the literal's string1273// representation. This is not public API other than for quote.1274#[doc(hidden)]1275pub unsafe fn from_str_unchecked(repr: &str) -> Self {1276Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })1277}1278}12791280impl FromStr for Literal {1281type Err = LexError;12821283fn from_str(repr: &str) -> Result<Self, LexError> {1284match imp::Literal::from_str_checked(repr) {1285Ok(lit) => Ok(Literal::_new(lit)),1286Err(lex) => Err(LexError {1287inner: lex,1288_marker: MARKER,1289}),1290}1291}1292}12931294impl Debug for Literal {1295fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {1296Debug::fmt(&self.inner, f)1297}1298}12991300impl Display for Literal {1301fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {1302Display::fmt(&self.inner, f)1303}1304}13051306/// Public implementation details for the `TokenStream` type, such as iterators.1307pub mod token_stream {1308use crate::marker::{ProcMacroAutoTraits, MARKER};1309use crate::{imp, TokenTree};1310use core::fmt::{self, Debug};13111312pub use crate::TokenStream;13131314/// An iterator over `TokenStream`'s `TokenTree`s.1315///1316/// The iteration is "shallow", e.g. the iterator doesn't recurse into1317/// delimited groups, and returns whole groups as token trees.1318#[derive(Clone)]1319pub struct IntoIter {1320inner: imp::TokenTreeIter,1321_marker: ProcMacroAutoTraits,1322}13231324impl Iterator for IntoIter {1325type Item = TokenTree;13261327fn next(&mut self) -> Option<TokenTree> {1328self.inner.next()1329}13301331fn size_hint(&self) -> (usize, Option<usize>) {1332self.inner.size_hint()1333}1334}13351336impl Debug for IntoIter {1337fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {1338f.write_str("TokenStream ")?;1339f.debug_list().entries(self.clone()).finish()1340}1341}13421343impl IntoIterator for TokenStream {1344type Item = TokenTree;1345type IntoIter = IntoIter;13461347fn into_iter(self) -> IntoIter {1348IntoIter {1349inner: self.inner.into_iter(),1350_marker: MARKER,1351}1352}1353}1354}135513561357