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