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