Skip to main content

proc_macro2/
lib.rs

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//! [`proc_macro`]: https://doc.rust-lang.org/proc_macro/
13//!
14//! - **Bring proc-macro-like functionality to other contexts like build.rs and
15//!   main.rs.** Types from `proc_macro` are entirely specific to procedural
16//!   macros and cannot ever exist in code outside of a procedural macro.
17//!   Meanwhile `proc_macro2` types may exist anywhere including non-macro code.
18//!   By developing foundational libraries like [syn] and [quote] against
19//!   `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem
20//!   becomes easily applicable to many other use cases and we avoid
21//!   reimplementing non-macro equivalents of those libraries.
22//!
23//! - **Make procedural macros unit testable.** As a consequence of being
24//!   specific to procedural macros, nothing that uses `proc_macro` can be
25//!   executed from a unit test. In order for helper libraries or components of
26//!   a macro to be testable in isolation, they must be implemented using
27//!   `proc_macro2`.
28//!
29//! [syn]: https://github.com/dtolnay/syn
30//! [quote]: https://github.com/dtolnay/quote
31//!
32//! # Usage
33//!
34//! The skeleton of a typical procedural macro typically looks like this:
35//!
36//! ```
37//! extern crate proc_macro;
38//!
39//! # const IGNORE: &str = stringify! {
40//! #[proc_macro_derive(MyDerive)]
41//! # };
42//! # #[cfg(wrap_proc_macro)]
43//! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
44//!     let input = proc_macro2::TokenStream::from(input);
45//!
46//!     let output: proc_macro2::TokenStream = {
47//!         /* transform input */
48//!         # input
49//!     };
50//!
51//!     proc_macro::TokenStream::from(output)
52//! }
53//! ```
54//!
55//! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to
56//! propagate parse errors correctly back to the compiler when parsing fails.
57//!
58//! [`parse_macro_input!`]: https://docs.rs/syn/2.0/syn/macro.parse_macro_input.html
59//!
60//! # Unstable features
61//!
62//! The default feature set of proc-macro2 tracks the most recent stable
63//! compiler API. Functionality in `proc_macro` that is not yet stable is not
64//! exposed by proc-macro2 by default.
65//!
66//! To opt into the additional APIs available in the most recent nightly
67//! compiler, the `procmacro2_semver_exempt` config flag must be passed to
68//! rustc. We will polyfill those nightly-only APIs back to Rust 1.56.0. As
69//! these are unstable APIs that track the nightly compiler, minor versions of
70//! proc-macro2 may make breaking changes to them at any time.
71//!
72//! ```sh
73//! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build
74//! ```
75//!
76//! Note that this must not only be done for your crate, but for any crate that
77//! depends on your crate. This infectious nature is intentional, as it serves
78//! as a reminder that you are outside of the normal semver guarantees.
79//!
80//! Semver exempt methods are marked as such in the proc-macro2 documentation.
81//!
82//! # Thread-Safety
83//!
84//! Most types in this crate are `!Sync` because the underlying compiler
85//! types make use of thread-local memory, meaning they cannot be accessed from
86//! a different thread.
87
88// Proc-macro2 types in rustdoc of other crates get linked to here.
89#![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.80")]
90#![cfg_attr(any(proc_macro_span, super_unstable), feature(proc_macro_span))]
91#![cfg_attr(super_unstable, feature(proc_macro_def_site))]
92#![cfg_attr(doc_cfg, feature(doc_cfg))]
93#![deny(unsafe_op_in_unsafe_fn)]
94#![allow(
95    clippy::cast_lossless,
96    clippy::cast_possible_truncation,
97    clippy::checked_conversions,
98    clippy::doc_markdown,
99    clippy::incompatible_msrv,
100    clippy::items_after_statements,
101    clippy::iter_without_into_iter,
102    clippy::let_underscore_untyped,
103    clippy::manual_assert,
104    clippy::manual_range_contains,
105    clippy::missing_safety_doc,
106    clippy::must_use_candidate,
107    clippy::needless_doctest_main,
108    clippy::new_without_default,
109    clippy::return_self_not_must_use,
110    clippy::shadow_unrelated,
111    clippy::trivially_copy_pass_by_ref,
112    clippy::unnecessary_wraps,
113    clippy::unused_self,
114    clippy::used_underscore_binding,
115    clippy::vec_init_then_push
116)]
117
118#[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))]
119compile_error! {"\
120    Something is not right. If you've tried to turn on \
121    procmacro2_semver_exempt, you need to ensure that it \
122    is turned on for the compilation of the proc-macro2 \
123    build script as well.
124"}
125
126#[cfg(all(
127    procmacro2_nightly_testing,
128    feature = "proc-macro",
129    not(proc_macro_span)
130))]
131compile_error! {"\
132    Build script probe failed to compile.
133"}
134
135extern crate alloc;
136
137#[cfg(feature = "proc-macro")]
138extern crate proc_macro;
139
140mod marker;
141mod parse;
142mod rcvec;
143
144#[cfg(wrap_proc_macro)]
145mod detection;
146
147// Public for proc_macro2::fallback::force() and unforce(), but those are quite
148// a niche use case so we omit it from rustdoc.
149#[doc(hidden)]
150pub mod fallback;
151
152pub mod extra;
153
154#[cfg(not(wrap_proc_macro))]
155use crate::fallback as imp;
156#[path = "wrapper.rs"]
157#[cfg(wrap_proc_macro)]
158mod imp;
159
160#[cfg(span_locations)]
161mod location;
162
163use crate::extra::DelimSpan;
164use crate::marker::{ProcMacroAutoTraits, MARKER};
165use core::cmp::Ordering;
166use core::fmt::{self, Debug, Display};
167use core::hash::{Hash, Hasher};
168#[cfg(span_locations)]
169use core::ops::Range;
170use core::ops::RangeBounds;
171use core::str::FromStr;
172use std::error::Error;
173use std::ffi::CStr;
174#[cfg(procmacro2_semver_exempt)]
175use std::path::PathBuf;
176
177#[cfg(span_locations)]
178#[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))]
179pub use crate::location::LineColumn;
180
181/// An abstract stream of tokens, or more concretely a sequence of token trees.
182///
183/// This type provides interfaces for iterating over token trees and for
184/// collecting token trees into one stream.
185///
186/// Token stream is both the input and output of `#[proc_macro]`,
187/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
188#[derive(Clone)]
189pub struct TokenStream {
190    inner: imp::TokenStream,
191    _marker: ProcMacroAutoTraits,
192}
193
194/// Error returned from `TokenStream::from_str`.
195pub struct LexError {
196    inner: imp::LexError,
197    _marker: ProcMacroAutoTraits,
198}
199
200impl TokenStream {
201    fn _new(inner: imp::TokenStream) -> Self {
202        TokenStream {
203            inner,
204            _marker: MARKER,
205        }
206    }
207
208    fn _new_fallback(inner: fallback::TokenStream) -> Self {
209        TokenStream {
210            inner: inner.into(),
211            _marker: MARKER,
212        }
213    }
214
215    /// Returns an empty `TokenStream` containing no token trees.
216    pub fn new() -> Self {
217        TokenStream::_new(imp::TokenStream::new())
218    }
219
220    /// Checks if this `TokenStream` is empty.
221    pub fn is_empty(&self) -> bool {
222        self.inner.is_empty()
223    }
224}
225
226/// `TokenStream::default()` returns an empty stream,
227/// i.e. this is equivalent with `TokenStream::new()`.
228impl Default for TokenStream {
229    fn default() -> Self {
230        TokenStream::new()
231    }
232}
233
234/// Attempts to break the string into tokens and parse those tokens into a token
235/// stream.
236///
237/// May fail for a number of reasons, for example, if the string contains
238/// unbalanced delimiters or characters not existing in the language.
239///
240/// NOTE: Some errors may cause panics instead of returning `LexError`. We
241/// reserve the right to change these errors into `LexError`s later.
242impl FromStr for TokenStream {
243    type Err = LexError;
244
245    fn from_str(src: &str) -> Result<TokenStream, LexError> {
246        let e = src.parse().map_err(|e| LexError {
247            inner: e,
248            _marker: MARKER,
249        })?;
250        Ok(TokenStream::_new(e))
251    }
252}
253
254#[cfg(feature = "proc-macro")]
255#[cfg_attr(doc_cfg, doc(cfg(feature = "proc-macro")))]
256impl From<proc_macro::TokenStream> for TokenStream {
257    fn from(inner: proc_macro::TokenStream) -> Self {
258        TokenStream::_new(inner.into())
259    }
260}
261
262#[cfg(feature = "proc-macro")]
263#[cfg_attr(doc_cfg, doc(cfg(feature = "proc-macro")))]
264impl From<TokenStream> for proc_macro::TokenStream {
265    fn from(inner: TokenStream) -> Self {
266        inner.inner.into()
267    }
268}
269
270impl From<TokenTree> for TokenStream {
271    fn from(token: TokenTree) -> Self {
272        TokenStream::_new(imp::TokenStream::from(token))
273    }
274}
275
276impl Extend<TokenTree> for TokenStream {
277    fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
278        self.inner.extend(streams);
279    }
280}
281
282impl Extend<TokenStream> for TokenStream {
283    fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
284        self.inner
285            .extend(streams.into_iter().map(|stream| stream.inner));
286    }
287}
288
289/// Collects a number of token trees into a single stream.
290impl FromIterator<TokenTree> for TokenStream {
291    fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
292        TokenStream::_new(streams.into_iter().collect())
293    }
294}
295impl FromIterator<TokenStream> for TokenStream {
296    fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
297        TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
298    }
299}
300
301/// Prints the token stream as a string that is supposed to be losslessly
302/// convertible back into the same token stream (modulo spans), except for
303/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
304/// numeric literals.
305impl Display for TokenStream {
306    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
307        Display::fmt(&self.inner, f)
308    }
309}
310
311/// Prints token in a form convenient for debugging.
312impl Debug for TokenStream {
313    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
314        Debug::fmt(&self.inner, f)
315    }
316}
317
318impl LexError {
319    pub fn span(&self) -> Span {
320        Span::_new(self.inner.span())
321    }
322}
323
324impl Debug for LexError {
325    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
326        Debug::fmt(&self.inner, f)
327    }
328}
329
330impl Display for LexError {
331    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
332        Display::fmt(&self.inner, f)
333    }
334}
335
336impl Error for LexError {}
337
338/// The source file of a given `Span`.
339///
340/// This type is semver exempt and not exposed by default.
341#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
342#[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))]
343#[derive(Clone, PartialEq, Eq)]
344pub struct SourceFile {
345    inner: imp::SourceFile,
346    _marker: ProcMacroAutoTraits,
347}
348
349#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
350impl SourceFile {
351    fn _new(inner: imp::SourceFile) -> Self {
352        SourceFile {
353            inner,
354            _marker: MARKER,
355        }
356    }
357
358    /// Get the path to this source file.
359    ///
360    /// ### Note
361    ///
362    /// If the code span associated with this `SourceFile` was generated by an
363    /// external macro, this may not be an actual path on the filesystem. Use
364    /// [`is_real`] to check.
365    ///
366    /// Also note that even if `is_real` returns `true`, if
367    /// `--remap-path-prefix` was passed on the command line, the path as given
368    /// may not actually be valid.
369    ///
370    /// [`is_real`]: #method.is_real
371    pub fn path(&self) -> PathBuf {
372        self.inner.path()
373    }
374
375    /// Returns `true` if this source file is a real source file, and not
376    /// generated by an external macro's expansion.
377    pub fn is_real(&self) -> bool {
378        self.inner.is_real()
379    }
380}
381
382#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
383impl Debug for SourceFile {
384    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
385        Debug::fmt(&self.inner, f)
386    }
387}
388
389/// A region of source code, along with macro expansion information.
390#[derive(Copy, Clone)]
391pub struct Span {
392    inner: imp::Span,
393    _marker: ProcMacroAutoTraits,
394}
395
396impl Span {
397    fn _new(inner: imp::Span) -> Self {
398        Span {
399            inner,
400            _marker: MARKER,
401        }
402    }
403
404    fn _new_fallback(inner: fallback::Span) -> Self {
405        Span {
406            inner: inner.into(),
407            _marker: MARKER,
408        }
409    }
410
411    /// The span of the invocation of the current procedural macro.
412    ///
413    /// Identifiers created with this span will be resolved as if they were
414    /// written directly at the macro call location (call-site hygiene) and
415    /// other code at the macro call site will be able to refer to them as well.
416    pub fn call_site() -> Self {
417        Span::_new(imp::Span::call_site())
418    }
419
420    /// The span located at the invocation of the procedural macro, but with
421    /// local variables, labels, and `$crate` resolved at the definition site
422    /// of the macro. This is the same hygiene behavior as `macro_rules`.
423    pub fn mixed_site() -> Self {
424        Span::_new(imp::Span::mixed_site())
425    }
426
427    /// A span that resolves at the macro definition site.
428    ///
429    /// This method is semver exempt and not exposed by default.
430    #[cfg(procmacro2_semver_exempt)]
431    #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))]
432    pub fn def_site() -> Self {
433        Span::_new(imp::Span::def_site())
434    }
435
436    /// Creates a new span with the same line/column information as `self` but
437    /// that resolves symbols as though it were at `other`.
438    pub fn resolved_at(&self, other: Span) -> Span {
439        Span::_new(self.inner.resolved_at(other.inner))
440    }
441
442    /// Creates a new span with the same name resolution behavior as `self` but
443    /// with the line/column information of `other`.
444    pub fn located_at(&self, other: Span) -> Span {
445        Span::_new(self.inner.located_at(other.inner))
446    }
447
448    /// Convert `proc_macro2::Span` to `proc_macro::Span`.
449    ///
450    /// This method is available when building with a nightly compiler, or when
451    /// building with rustc 1.29+ *without* semver exempt features.
452    ///
453    /// # Panics
454    ///
455    /// Panics if called from outside of a procedural macro. Unlike
456    /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
457    /// the context of a procedural macro invocation.
458    #[cfg(wrap_proc_macro)]
459    pub fn unwrap(self) -> proc_macro::Span {
460        self.inner.unwrap()
461    }
462
463    // Soft deprecated. Please use Span::unwrap.
464    #[cfg(wrap_proc_macro)]
465    #[doc(hidden)]
466    pub fn unstable(self) -> proc_macro::Span {
467        self.unwrap()
468    }
469
470    /// The original source file into which this span points.
471    ///
472    /// This method is semver exempt and not exposed by default.
473    #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
474    #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))]
475    pub fn source_file(&self) -> SourceFile {
476        SourceFile::_new(self.inner.source_file())
477    }
478
479    /// Returns the span's byte position range in the source file.
480    ///
481    /// This method requires the `"span-locations"` feature to be enabled.
482    ///
483    /// When executing in a procedural macro context, the returned range is only
484    /// accurate if compiled with a nightly toolchain. The stable toolchain does
485    /// not have this information available. When executing outside of a
486    /// procedural macro, such as main.rs or build.rs, the byte range is always
487    /// accurate regardless of toolchain.
488    #[cfg(span_locations)]
489    #[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))]
490    pub fn byte_range(&self) -> Range<usize> {
491        self.inner.byte_range()
492    }
493
494    /// Get the starting line/column in the source file for this span.
495    ///
496    /// This method requires the `"span-locations"` feature to be enabled.
497    ///
498    /// When executing in a procedural macro context, the returned line/column
499    /// are only meaningful if compiled with a nightly toolchain. The stable
500    /// toolchain does not have this information available. When executing
501    /// outside of a procedural macro, such as main.rs or build.rs, the
502    /// line/column are always meaningful regardless of toolchain.
503    #[cfg(span_locations)]
504    #[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))]
505    pub fn start(&self) -> LineColumn {
506        self.inner.start()
507    }
508
509    /// Get the ending line/column in the source file for this span.
510    ///
511    /// This method requires the `"span-locations"` feature to be enabled.
512    ///
513    /// When executing in a procedural macro context, the returned line/column
514    /// are only meaningful if compiled with a nightly toolchain. The stable
515    /// toolchain does not have this information available. When executing
516    /// outside of a procedural macro, such as main.rs or build.rs, the
517    /// line/column are always meaningful regardless of toolchain.
518    #[cfg(span_locations)]
519    #[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))]
520    pub fn end(&self) -> LineColumn {
521        self.inner.end()
522    }
523
524    /// Create a new span encompassing `self` and `other`.
525    ///
526    /// Returns `None` if `self` and `other` are from different files.
527    ///
528    /// Warning: the underlying [`proc_macro::Span::join`] method is
529    /// nightly-only. When called from within a procedural macro not using a
530    /// nightly compiler, this method will always return `None`.
531    ///
532    /// [`proc_macro::Span::join`]: https://doc.rust-lang.org/proc_macro/struct.Span.html#method.join
533    pub fn join(&self, other: Span) -> Option<Span> {
534        self.inner.join(other.inner).map(Span::_new)
535    }
536
537    /// Compares two spans to see if they're equal.
538    ///
539    /// This method is semver exempt and not exposed by default.
540    #[cfg(procmacro2_semver_exempt)]
541    #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))]
542    pub fn eq(&self, other: &Span) -> bool {
543        self.inner.eq(&other.inner)
544    }
545
546    /// Returns the source text behind a span. This preserves the original
547    /// source code, including spaces and comments. It only returns a result if
548    /// the span corresponds to real source code.
549    ///
550    /// Note: The observable result of a macro should only rely on the tokens
551    /// and not on this source text. The result of this function is a best
552    /// effort to be used for diagnostics only.
553    pub fn source_text(&self) -> Option<String> {
554        self.inner.source_text()
555    }
556}
557
558/// Prints a span in a form convenient for debugging.
559impl Debug for Span {
560    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
561        Debug::fmt(&self.inner, f)
562    }
563}
564
565/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
566#[derive(Clone)]
567pub enum TokenTree {
568    /// A token stream surrounded by bracket delimiters.
569    Group(Group),
570    /// An identifier.
571    Ident(Ident),
572    /// A single punctuation character (`+`, `,`, `$`, etc.).
573    Punct(Punct),
574    /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
575    Literal(Literal),
576}
577
578impl TokenTree {
579    /// Returns the span of this tree, delegating to the `span` method of
580    /// the contained token or a delimited stream.
581    pub fn span(&self) -> Span {
582        match self {
583            TokenTree::Group(t) => t.span(),
584            TokenTree::Ident(t) => t.span(),
585            TokenTree::Punct(t) => t.span(),
586            TokenTree::Literal(t) => t.span(),
587        }
588    }
589
590    /// Configures the span for *only this token*.
591    ///
592    /// Note that if this token is a `Group` then this method will not configure
593    /// the span of each of the internal tokens, this will simply delegate to
594    /// the `set_span` method of each variant.
595    pub fn set_span(&mut self, span: Span) {
596        match self {
597            TokenTree::Group(t) => t.set_span(span),
598            TokenTree::Ident(t) => t.set_span(span),
599            TokenTree::Punct(t) => t.set_span(span),
600            TokenTree::Literal(t) => t.set_span(span),
601        }
602    }
603}
604
605impl From<Group> for TokenTree {
606    fn from(g: Group) -> Self {
607        TokenTree::Group(g)
608    }
609}
610
611impl From<Ident> for TokenTree {
612    fn from(g: Ident) -> Self {
613        TokenTree::Ident(g)
614    }
615}
616
617impl From<Punct> for TokenTree {
618    fn from(g: Punct) -> Self {
619        TokenTree::Punct(g)
620    }
621}
622
623impl From<Literal> for TokenTree {
624    fn from(g: Literal) -> Self {
625        TokenTree::Literal(g)
626    }
627}
628
629/// Prints the token tree as a string that is supposed to be losslessly
630/// convertible back into the same token tree (modulo spans), except for
631/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
632/// numeric literals.
633impl Display for TokenTree {
634    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
635        match self {
636            TokenTree::Group(t) => Display::fmt(t, f),
637            TokenTree::Ident(t) => Display::fmt(t, f),
638            TokenTree::Punct(t) => Display::fmt(t, f),
639            TokenTree::Literal(t) => Display::fmt(t, f),
640        }
641    }
642}
643
644/// Prints token tree in a form convenient for debugging.
645impl Debug for TokenTree {
646    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
647        // Each of these has the name in the struct type in the derived debug,
648        // so don't bother with an extra layer of indirection
649        match self {
650            TokenTree::Group(t) => Debug::fmt(t, f),
651            TokenTree::Ident(t) => {
652                let mut debug = f.debug_struct("Ident");
653                debug.field("sym", &format_args!("{}", t));
654                imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
655                debug.finish()
656            }
657            TokenTree::Punct(t) => Debug::fmt(t, f),
658            TokenTree::Literal(t) => Debug::fmt(t, f),
659        }
660    }
661}
662
663/// A delimited token stream.
664///
665/// A `Group` internally contains a `TokenStream` which is surrounded by
666/// `Delimiter`s.
667#[derive(Clone)]
668pub struct Group {
669    inner: imp::Group,
670}
671
672/// Describes how a sequence of token trees is delimited.
673#[derive(Copy, Clone, Debug, Eq, PartialEq)]
674pub enum Delimiter {
675    /// `( ... )`
676    Parenthesis,
677    /// `{ ... }`
678    Brace,
679    /// `[ ... ]`
680    Bracket,
681    /// `Ø ... Ø`
682    ///
683    /// An implicit delimiter, that may, for example, appear around tokens
684    /// coming from a "macro variable" `$var`. It is important to preserve
685    /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
686    /// Implicit delimiters may not survive roundtrip of a token stream through
687    /// a string.
688    None,
689}
690
691impl Group {
692    fn _new(inner: imp::Group) -> Self {
693        Group { inner }
694    }
695
696    fn _new_fallback(inner: fallback::Group) -> Self {
697        Group {
698            inner: inner.into(),
699        }
700    }
701
702    /// Creates a new `Group` with the given delimiter and token stream.
703    ///
704    /// This constructor will set the span for this group to
705    /// `Span::call_site()`. To change the span you can use the `set_span`
706    /// method below.
707    pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
708        Group {
709            inner: imp::Group::new(delimiter, stream.inner),
710        }
711    }
712
713    /// Returns the punctuation used as the delimiter for this group: a set of
714    /// parentheses, square brackets, or curly braces.
715    pub fn delimiter(&self) -> Delimiter {
716        self.inner.delimiter()
717    }
718
719    /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
720    ///
721    /// Note that the returned token stream does not include the delimiter
722    /// returned above.
723    pub fn stream(&self) -> TokenStream {
724        TokenStream::_new(self.inner.stream())
725    }
726
727    /// Returns the span for the delimiters of this token stream, spanning the
728    /// entire `Group`.
729    ///
730    /// ```text
731    /// pub fn span(&self) -> Span {
732    ///            ^^^^^^^
733    /// ```
734    pub fn span(&self) -> Span {
735        Span::_new(self.inner.span())
736    }
737
738    /// Returns the span pointing to the opening delimiter of this group.
739    ///
740    /// ```text
741    /// pub fn span_open(&self) -> Span {
742    ///                 ^
743    /// ```
744    pub fn span_open(&self) -> Span {
745        Span::_new(self.inner.span_open())
746    }
747
748    /// Returns the span pointing to the closing delimiter of this group.
749    ///
750    /// ```text
751    /// pub fn span_close(&self) -> Span {
752    ///                        ^
753    /// ```
754    pub fn span_close(&self) -> Span {
755        Span::_new(self.inner.span_close())
756    }
757
758    /// Returns an object that holds this group's `span_open()` and
759    /// `span_close()` together (in a more compact representation than holding
760    /// those 2 spans individually).
761    pub fn delim_span(&self) -> DelimSpan {
762        DelimSpan::new(&self.inner)
763    }
764
765    /// Configures the span for this `Group`'s delimiters, but not its internal
766    /// tokens.
767    ///
768    /// This method will **not** set the span of all the internal tokens spanned
769    /// by this group, but rather it will only set the span of the delimiter
770    /// tokens at the level of the `Group`.
771    pub fn set_span(&mut self, span: Span) {
772        self.inner.set_span(span.inner);
773    }
774}
775
776/// Prints the group as a string that should be losslessly convertible back
777/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
778/// with `Delimiter::None` delimiters.
779impl Display for Group {
780    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
781        Display::fmt(&self.inner, formatter)
782    }
783}
784
785impl Debug for Group {
786    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
787        Debug::fmt(&self.inner, formatter)
788    }
789}
790
791/// A `Punct` is a single punctuation character like `+`, `-` or `#`.
792///
793/// Multicharacter operators like `+=` are represented as two instances of
794/// `Punct` with different forms of `Spacing` returned.
795#[derive(Clone)]
796pub struct Punct {
797    ch: char,
798    spacing: Spacing,
799    span: Span,
800}
801
802/// Whether a `Punct` is followed immediately by another `Punct` or followed by
803/// another token or whitespace.
804#[derive(Copy, Clone, Debug, Eq, PartialEq)]
805pub enum Spacing {
806    /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
807    Alone,
808    /// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.
809    ///
810    /// Additionally, single quote `'` can join with identifiers to form
811    /// lifetimes `'ident`.
812    Joint,
813}
814
815impl Punct {
816    /// Creates a new `Punct` from the given character and spacing.
817    ///
818    /// The `ch` argument must be a valid punctuation character permitted by the
819    /// language, otherwise the function will panic.
820    ///
821    /// The returned `Punct` will have the default span of `Span::call_site()`
822    /// which can be further configured with the `set_span` method below.
823    pub fn new(ch: char, spacing: Spacing) -> Self {
824        Punct {
825            ch,
826            spacing,
827            span: Span::call_site(),
828        }
829    }
830
831    /// Returns the value of this punctuation character as `char`.
832    pub fn as_char(&self) -> char {
833        self.ch
834    }
835
836    /// Returns the spacing of this punctuation character, indicating whether
837    /// it's immediately followed by another `Punct` in the token stream, so
838    /// they can potentially be combined into a multicharacter operator
839    /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
840    /// so the operator has certainly ended.
841    pub fn spacing(&self) -> Spacing {
842        self.spacing
843    }
844
845    /// Returns the span for this punctuation character.
846    pub fn span(&self) -> Span {
847        self.span
848    }
849
850    /// Configure the span for this punctuation character.
851    pub fn set_span(&mut self, span: Span) {
852        self.span = span;
853    }
854}
855
856/// Prints the punctuation character as a string that should be losslessly
857/// convertible back into the same character.
858impl Display for Punct {
859    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
860        Display::fmt(&self.ch, f)
861    }
862}
863
864impl Debug for Punct {
865    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
866        let mut debug = fmt.debug_struct("Punct");
867        debug.field("char", &self.ch);
868        debug.field("spacing", &self.spacing);
869        imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
870        debug.finish()
871    }
872}
873
874/// A word of Rust code, which may be a keyword or legal variable name.
875///
876/// An identifier consists of at least one Unicode code point, the first of
877/// which has the XID_Start property and the rest of which have the XID_Continue
878/// property.
879///
880/// - The empty string is not an identifier. Use `Option<Ident>`.
881/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
882///
883/// An identifier constructed with `Ident::new` is permitted to be a Rust
884/// keyword, though parsing one through its [`Parse`] implementation rejects
885/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
886/// behaviour of `Ident::new`.
887///
888/// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html
889///
890/// # Examples
891///
892/// A new ident can be created from a string using the `Ident::new` function.
893/// A span must be provided explicitly which governs the name resolution
894/// behavior of the resulting identifier.
895///
896/// ```
897/// use proc_macro2::{Ident, Span};
898///
899/// fn main() {
900///     let call_ident = Ident::new("calligraphy", Span::call_site());
901///
902///     println!("{}", call_ident);
903/// }
904/// ```
905///
906/// An ident can be interpolated into a token stream using the `quote!` macro.
907///
908/// ```
909/// use proc_macro2::{Ident, Span};
910/// use quote::quote;
911///
912/// fn main() {
913///     let ident = Ident::new("demo", Span::call_site());
914///
915///     // Create a variable binding whose name is this ident.
916///     let expanded = quote! { let #ident = 10; };
917///
918///     // Create a variable binding with a slightly different name.
919///     let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
920///     let expanded = quote! { let #temp_ident = 10; };
921/// }
922/// ```
923///
924/// A string representation of the ident is available through the `to_string()`
925/// method.
926///
927/// ```
928/// # use proc_macro2::{Ident, Span};
929/// #
930/// # let ident = Ident::new("another_identifier", Span::call_site());
931/// #
932/// // Examine the ident as a string.
933/// let ident_string = ident.to_string();
934/// if ident_string.len() > 60 {
935///     println!("Very long identifier: {}", ident_string)
936/// }
937/// ```
938#[derive(Clone)]
939pub struct Ident {
940    inner: imp::Ident,
941    _marker: ProcMacroAutoTraits,
942}
943
944impl Ident {
945    fn _new(inner: imp::Ident) -> Self {
946        Ident {
947            inner,
948            _marker: MARKER,
949        }
950    }
951
952    /// Creates a new `Ident` with the given `string` as well as the specified
953    /// `span`.
954    ///
955    /// The `string` argument must be a valid identifier permitted by the
956    /// language, otherwise the function will panic.
957    ///
958    /// Note that `span`, currently in rustc, configures the hygiene information
959    /// for this identifier.
960    ///
961    /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
962    /// hygiene meaning that identifiers created with this span will be resolved
963    /// as if they were written directly at the location of the macro call, and
964    /// other code at the macro call site will be able to refer to them as well.
965    ///
966    /// Later spans like `Span::def_site()` will allow to opt-in to
967    /// "definition-site" hygiene meaning that identifiers created with this
968    /// span will be resolved at the location of the macro definition and other
969    /// code at the macro call site will not be able to refer to them.
970    ///
971    /// Due to the current importance of hygiene this constructor, unlike other
972    /// tokens, requires a `Span` to be specified at construction.
973    ///
974    /// # Panics
975    ///
976    /// Panics if the input string is neither a keyword nor a legal variable
977    /// name. If you are not sure whether the string contains an identifier and
978    /// need to handle an error case, use
979    /// <a href="https://docs.rs/syn/2.0/syn/fn.parse_str.html"><code
980    ///   style="padding-right:0;">syn::parse_str</code></a><code
981    ///   style="padding-left:0;">::&lt;Ident&gt;</code>
982    /// rather than `Ident::new`.
983    #[track_caller]
984    pub fn new(string: &str, span: Span) -> Self {
985        Ident::_new(imp::Ident::new_checked(string, span.inner))
986    }
987
988    /// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The
989    /// `string` argument must be a valid identifier permitted by the language
990    /// (including keywords, e.g. `fn`). Keywords which are usable in path
991    /// segments (e.g. `self`, `super`) are not supported, and will cause a
992    /// panic.
993    #[track_caller]
994    pub fn new_raw(string: &str, span: Span) -> Self {
995        Ident::_new(imp::Ident::new_raw_checked(string, span.inner))
996    }
997
998    /// Returns the span of this `Ident`.
999    pub fn span(&self) -> Span {
1000        Span::_new(self.inner.span())
1001    }
1002
1003    /// Configures the span of this `Ident`, possibly changing its hygiene
1004    /// context.
1005    pub fn set_span(&mut self, span: Span) {
1006        self.inner.set_span(span.inner);
1007    }
1008}
1009
1010impl PartialEq for Ident {
1011    fn eq(&self, other: &Ident) -> bool {
1012        self.inner == other.inner
1013    }
1014}
1015
1016impl<T> PartialEq<T> for Ident
1017where
1018    T: ?Sized + AsRef<str>,
1019{
1020    fn eq(&self, other: &T) -> bool {
1021        self.inner == other
1022    }
1023}
1024
1025impl Eq for Ident {}
1026
1027impl PartialOrd for Ident {
1028    fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
1029        Some(self.cmp(other))
1030    }
1031}
1032
1033impl Ord for Ident {
1034    fn cmp(&self, other: &Ident) -> Ordering {
1035        self.to_string().cmp(&other.to_string())
1036    }
1037}
1038
1039impl Hash for Ident {
1040    fn hash<H: Hasher>(&self, hasher: &mut H) {
1041        self.to_string().hash(hasher);
1042    }
1043}
1044
1045/// Prints the identifier as a string that should be losslessly convertible back
1046/// into the same identifier.
1047impl Display for Ident {
1048    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1049        Display::fmt(&self.inner, f)
1050    }
1051}
1052
1053impl Debug for Ident {
1054    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1055        Debug::fmt(&self.inner, f)
1056    }
1057}
1058
1059/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
1060/// byte character (`b'a'`), an integer or floating point number with or without
1061/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1062///
1063/// Boolean literals like `true` and `false` do not belong here, they are
1064/// `Ident`s.
1065#[derive(Clone)]
1066pub struct Literal {
1067    inner: imp::Literal,
1068    _marker: ProcMacroAutoTraits,
1069}
1070
1071macro_rules! suffixed_int_literals {
1072    ($($name:ident => $kind:ident,)*) => ($(
1073        /// Creates a new suffixed integer literal with the specified value.
1074        ///
1075        /// This function will create an integer like `1u32` where the integer
1076        /// value specified is the first part of the token and the integral is
1077        /// also suffixed at the end. Literals created from negative numbers may
1078        /// not survive roundtrips through `TokenStream` or strings and may be
1079        /// broken into two tokens (`-` and positive literal).
1080        ///
1081        /// Literals created through this method have the `Span::call_site()`
1082        /// span by default, which can be configured with the `set_span` method
1083        /// below.
1084        pub fn $name(n: $kind) -> Literal {
1085            Literal::_new(imp::Literal::$name(n))
1086        }
1087    )*)
1088}
1089
1090macro_rules! unsuffixed_int_literals {
1091    ($($name:ident => $kind:ident,)*) => ($(
1092        /// Creates a new unsuffixed integer literal with the specified value.
1093        ///
1094        /// This function will create an integer like `1` where the integer
1095        /// value specified is the first part of the token. No suffix is
1096        /// specified on this token, meaning that invocations like
1097        /// `Literal::i8_unsuffixed(1)` are equivalent to
1098        /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
1099        /// may not survive roundtrips through `TokenStream` or strings and may
1100        /// be broken into two tokens (`-` and positive literal).
1101        ///
1102        /// Literals created through this method have the `Span::call_site()`
1103        /// span by default, which can be configured with the `set_span` method
1104        /// below.
1105        pub fn $name(n: $kind) -> Literal {
1106            Literal::_new(imp::Literal::$name(n))
1107        }
1108    )*)
1109}
1110
1111impl Literal {
1112    fn _new(inner: imp::Literal) -> Self {
1113        Literal {
1114            inner,
1115            _marker: MARKER,
1116        }
1117    }
1118
1119    fn _new_fallback(inner: fallback::Literal) -> Self {
1120        Literal {
1121            inner: inner.into(),
1122            _marker: MARKER,
1123        }
1124    }
1125
1126    suffixed_int_literals! {
1127        u8_suffixed => u8,
1128        u16_suffixed => u16,
1129        u32_suffixed => u32,
1130        u64_suffixed => u64,
1131        u128_suffixed => u128,
1132        usize_suffixed => usize,
1133        i8_suffixed => i8,
1134        i16_suffixed => i16,
1135        i32_suffixed => i32,
1136        i64_suffixed => i64,
1137        i128_suffixed => i128,
1138        isize_suffixed => isize,
1139    }
1140
1141    unsuffixed_int_literals! {
1142        u8_unsuffixed => u8,
1143        u16_unsuffixed => u16,
1144        u32_unsuffixed => u32,
1145        u64_unsuffixed => u64,
1146        u128_unsuffixed => u128,
1147        usize_unsuffixed => usize,
1148        i8_unsuffixed => i8,
1149        i16_unsuffixed => i16,
1150        i32_unsuffixed => i32,
1151        i64_unsuffixed => i64,
1152        i128_unsuffixed => i128,
1153        isize_unsuffixed => isize,
1154    }
1155
1156    /// Creates a new unsuffixed floating-point literal.
1157    ///
1158    /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1159    /// the float's value is emitted directly into the token but no suffix is
1160    /// used, so it may be inferred to be a `f64` later in the compiler.
1161    /// Literals created from negative numbers may not survive round-trips
1162    /// through `TokenStream` or strings and may be broken into two tokens (`-`
1163    /// and positive literal).
1164    ///
1165    /// # Panics
1166    ///
1167    /// This function requires that the specified float is finite, for example
1168    /// if it is infinity or NaN this function will panic.
1169    pub fn f64_unsuffixed(f: f64) -> Literal {
1170        assert!(f.is_finite());
1171        Literal::_new(imp::Literal::f64_unsuffixed(f))
1172    }
1173
1174    /// Creates a new suffixed floating-point literal.
1175    ///
1176    /// This constructor will create a literal like `1.0f64` where the value
1177    /// specified is the preceding part of the token and `f64` is the suffix of
1178    /// the token. This token will always be inferred to be an `f64` in the
1179    /// compiler. Literals created from negative numbers may not survive
1180    /// round-trips through `TokenStream` or strings and may be broken into two
1181    /// tokens (`-` and positive literal).
1182    ///
1183    /// # Panics
1184    ///
1185    /// This function requires that the specified float is finite, for example
1186    /// if it is infinity or NaN this function will panic.
1187    pub fn f64_suffixed(f: f64) -> Literal {
1188        assert!(f.is_finite());
1189        Literal::_new(imp::Literal::f64_suffixed(f))
1190    }
1191
1192    /// Creates a new unsuffixed floating-point literal.
1193    ///
1194    /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1195    /// the float's value is emitted directly into the token but no suffix is
1196    /// used, so it may be inferred to be a `f64` later in the compiler.
1197    /// Literals created from negative numbers may not survive round-trips
1198    /// through `TokenStream` or strings and may be broken into two tokens (`-`
1199    /// and positive literal).
1200    ///
1201    /// # Panics
1202    ///
1203    /// This function requires that the specified float is finite, for example
1204    /// if it is infinity or NaN this function will panic.
1205    pub fn f32_unsuffixed(f: f32) -> Literal {
1206        assert!(f.is_finite());
1207        Literal::_new(imp::Literal::f32_unsuffixed(f))
1208    }
1209
1210    /// Creates a new suffixed floating-point literal.
1211    ///
1212    /// This constructor will create a literal like `1.0f32` where the value
1213    /// specified is the preceding part of the token and `f32` is the suffix of
1214    /// the token. This token will always be inferred to be an `f32` in the
1215    /// compiler. Literals created from negative numbers may not survive
1216    /// round-trips through `TokenStream` or strings and may be broken into two
1217    /// tokens (`-` and positive literal).
1218    ///
1219    /// # Panics
1220    ///
1221    /// This function requires that the specified float is finite, for example
1222    /// if it is infinity or NaN this function will panic.
1223    pub fn f32_suffixed(f: f32) -> Literal {
1224        assert!(f.is_finite());
1225        Literal::_new(imp::Literal::f32_suffixed(f))
1226    }
1227
1228    /// String literal.
1229    pub fn string(string: &str) -> Literal {
1230        Literal::_new(imp::Literal::string(string))
1231    }
1232
1233    /// Character literal.
1234    pub fn character(ch: char) -> Literal {
1235        Literal::_new(imp::Literal::character(ch))
1236    }
1237
1238    /// Byte character literal.
1239    pub fn byte_character(byte: u8) -> Literal {
1240        Literal::_new(imp::Literal::byte_character(byte))
1241    }
1242
1243    /// Byte string literal.
1244    pub fn byte_string(bytes: &[u8]) -> Literal {
1245        Literal::_new(imp::Literal::byte_string(bytes))
1246    }
1247
1248    /// C string literal.
1249    pub fn c_string(string: &CStr) -> Literal {
1250        Literal::_new(imp::Literal::c_string(string))
1251    }
1252
1253    /// Returns the span encompassing this literal.
1254    pub fn span(&self) -> Span {
1255        Span::_new(self.inner.span())
1256    }
1257
1258    /// Configures the span associated for this literal.
1259    pub fn set_span(&mut self, span: Span) {
1260        self.inner.set_span(span.inner);
1261    }
1262
1263    /// Returns a `Span` that is a subset of `self.span()` containing only
1264    /// the source bytes in range `range`. Returns `None` if the would-be
1265    /// trimmed span is outside the bounds of `self`.
1266    ///
1267    /// Warning: the underlying [`proc_macro::Literal::subspan`] method is
1268    /// nightly-only. When called from within a procedural macro not using a
1269    /// nightly compiler, this method will always return `None`.
1270    ///
1271    /// [`proc_macro::Literal::subspan`]: https://doc.rust-lang.org/proc_macro/struct.Literal.html#method.subspan
1272    pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1273        self.inner.subspan(range).map(Span::_new)
1274    }
1275
1276    // Intended for the `quote!` macro to use when constructing a proc-macro2
1277    // token out of a macro_rules $:literal token, which is already known to be
1278    // a valid literal. This avoids reparsing/validating the literal's string
1279    // representation. This is not public API other than for quote.
1280    #[doc(hidden)]
1281    pub unsafe fn from_str_unchecked(repr: &str) -> Self {
1282        Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })
1283    }
1284}
1285
1286impl FromStr for Literal {
1287    type Err = LexError;
1288
1289    fn from_str(repr: &str) -> Result<Self, LexError> {
1290        repr.parse().map(Literal::_new).map_err(|inner| LexError {
1291            inner,
1292            _marker: MARKER,
1293        })
1294    }
1295}
1296
1297impl Debug for Literal {
1298    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1299        Debug::fmt(&self.inner, f)
1300    }
1301}
1302
1303impl Display for Literal {
1304    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1305        Display::fmt(&self.inner, f)
1306    }
1307}
1308
1309/// Public implementation details for the `TokenStream` type, such as iterators.
1310pub mod token_stream {
1311    use crate::marker::{ProcMacroAutoTraits, MARKER};
1312    use crate::{imp, TokenTree};
1313    use core::fmt::{self, Debug};
1314
1315    pub use crate::TokenStream;
1316
1317    /// An iterator over `TokenStream`'s `TokenTree`s.
1318    ///
1319    /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1320    /// delimited groups, and returns whole groups as token trees.
1321    #[derive(Clone)]
1322    pub struct IntoIter {
1323        inner: imp::TokenTreeIter,
1324        _marker: ProcMacroAutoTraits,
1325    }
1326
1327    impl Iterator for IntoIter {
1328        type Item = TokenTree;
1329
1330        fn next(&mut self) -> Option<TokenTree> {
1331            self.inner.next()
1332        }
1333
1334        fn size_hint(&self) -> (usize, Option<usize>) {
1335            self.inner.size_hint()
1336        }
1337    }
1338
1339    impl Debug for IntoIter {
1340        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1341            f.write_str("TokenStream ")?;
1342            f.debug_list().entries(self.clone()).finish()
1343        }
1344    }
1345
1346    impl IntoIterator for TokenStream {
1347        type Item = TokenTree;
1348        type IntoIter = IntoIter;
1349
1350        fn into_iter(self) -> IntoIter {
1351            IntoIter {
1352                inner: self.inner.into_iter(),
1353                _marker: MARKER,
1354            }
1355        }
1356    }
1357}