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