proc_macro2/lib.rs
1//! [![github]](https://github.com/dtolnay/proc-macro2) [![crates-io]](https://crates.io/crates/proc-macro2) [![docs-rs]](crate)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6//!
7//! <br>
8//!
9//! A wrapper around the procedural macro API of the compiler's [`proc_macro`]
10//! crate. This library serves two purposes:
11//!
12//! [`proc_macro`]: https://doc.rust-lang.org/proc_macro/
13//!
14//! - **Bring proc-macro-like functionality to other contexts like build.rs and
15//! main.rs.** Types from `proc_macro` are entirely specific to procedural
16//! macros and cannot ever exist in code outside of a procedural macro.
17//! Meanwhile `proc_macro2` types may exist anywhere including non-macro code.
18//! By developing foundational libraries like [syn] and [quote] against
19//! `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem
20//! becomes easily applicable to many other use cases and we avoid
21//! reimplementing non-macro equivalents of those libraries.
22//!
23//! - **Make procedural macros unit testable.** As a consequence of being
24//! specific to procedural macros, nothing that uses `proc_macro` can be
25//! executed from a unit test. In order for helper libraries or components of
26//! a macro to be testable in isolation, they must be implemented using
27//! `proc_macro2`.
28//!
29//! [syn]: https://github.com/dtolnay/syn
30//! [quote]: https://github.com/dtolnay/quote
31//!
32//! # Usage
33//!
34//! The skeleton of a typical procedural macro typically looks like this:
35//!
36//! ```
37//! extern crate proc_macro;
38//!
39//! # const IGNORE: &str = stringify! {
40//! #[proc_macro_derive(MyDerive)]
41//! # };
42//! # #[cfg(wrap_proc_macro)]
43//! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
44//! let input = proc_macro2::TokenStream::from(input);
45//!
46//! let output: proc_macro2::TokenStream = {
47//! /* transform input */
48//! # input
49//! };
50//!
51//! proc_macro::TokenStream::from(output)
52//! }
53//! ```
54//!
55//! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to
56//! propagate parse errors correctly back to the compiler when parsing fails.
57//!
58//! [`parse_macro_input!`]: https://docs.rs/syn/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.31.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.46")]
90#![cfg_attr(
91 any(proc_macro_span, super_unstable),
92 feature(proc_macro_span, proc_macro_span_shrink)
93)]
94#![cfg_attr(super_unstable, feature(proc_macro_def_site))]
95#![cfg_attr(doc_cfg, feature(doc_cfg))]
96#![allow(
97 clippy::cast_lossless,
98 clippy::cast_possible_truncation,
99 clippy::doc_markdown,
100 clippy::items_after_statements,
101 clippy::manual_assert,
102 clippy::must_use_candidate,
103 clippy::needless_doctest_main,
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
121#[cfg(use_proc_macro)]
122extern crate proc_macro;
123
124mod marker;
125mod parse;
126mod rcvec;
127
128#[cfg(wrap_proc_macro)]
129mod detection;
130
131// Public for proc_macro2::fallback::force() and unforce(), but those are quite
132// a niche use case so we omit it from rustdoc.
133#[doc(hidden)]
134pub mod fallback;
135
136#[cfg(not(wrap_proc_macro))]
137use crate::fallback as imp;
138#[path = "wrapper.rs"]
139#[cfg(wrap_proc_macro)]
140mod imp;
141
142use crate::marker::Marker;
143use core::cmp::Ordering;
144use core::fmt::{self, Debug, Display};
145use core::hash::{Hash, Hasher};
146use core::iter::FromIterator;
147use core::ops::RangeBounds;
148use core::str::FromStr;
149use std::error::Error;
150#[cfg(procmacro2_semver_exempt)]
151use std::path::PathBuf;
152
153/// An abstract stream of tokens, or more concretely a sequence of token trees.
154///
155/// This type provides interfaces for iterating over token trees and for
156/// collecting token trees into one stream.
157///
158/// Token stream is both the input and output of `#[proc_macro]`,
159/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
160#[derive(Clone)]
161pub struct TokenStream {
162 inner: imp::TokenStream,
163 _marker: Marker,
164}
165
166/// Error returned from `TokenStream::from_str`.
167pub struct LexError {
168 inner: imp::LexError,
169 _marker: Marker,
170}
171
172impl TokenStream {
173 fn _new(inner: imp::TokenStream) -> Self {
174 TokenStream {
175 inner,
176 _marker: Marker,
177 }
178 }
179
180 fn _new_stable(inner: fallback::TokenStream) -> Self {
181 TokenStream {
182 inner: inner.into(),
183 _marker: Marker,
184 }
185 }
186
187 /// Returns an empty `TokenStream` containing no token trees.
188 pub fn new() -> Self {
189 TokenStream::_new(imp::TokenStream::new())
190 }
191
192 /// Checks if this `TokenStream` is empty.
193 pub fn is_empty(&self) -> bool {
194 self.inner.is_empty()
195 }
196}
197
198/// `TokenStream::default()` returns an empty stream,
199/// i.e. this is equivalent with `TokenStream::new()`.
200impl Default for TokenStream {
201 fn default() -> Self {
202 TokenStream::new()
203 }
204}
205
206/// Attempts to break the string into tokens and parse those tokens into a token
207/// stream.
208///
209/// May fail for a number of reasons, for example, if the string contains
210/// unbalanced delimiters or characters not existing in the language.
211///
212/// NOTE: Some errors may cause panics instead of returning `LexError`. We
213/// reserve the right to change these errors into `LexError`s later.
214impl FromStr for TokenStream {
215 type Err = LexError;
216
217 fn from_str(src: &str) -> Result<TokenStream, LexError> {
218 let e = src.parse().map_err(|e| LexError {
219 inner: e,
220 _marker: Marker,
221 })?;
222 Ok(TokenStream::_new(e))
223 }
224}
225
226#[cfg(use_proc_macro)]
227impl From<proc_macro::TokenStream> for TokenStream {
228 fn from(inner: proc_macro::TokenStream) -> TokenStream {
229 TokenStream::_new(inner.into())
230 }
231}
232
233#[cfg(use_proc_macro)]
234impl From<TokenStream> for proc_macro::TokenStream {
235 fn from(inner: TokenStream) -> proc_macro::TokenStream {
236 inner.inner.into()
237 }
238}
239
240impl From<TokenTree> for TokenStream {
241 fn from(token: TokenTree) -> Self {
242 TokenStream::_new(imp::TokenStream::from(token))
243 }
244}
245
246impl Extend<TokenTree> for TokenStream {
247 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
248 self.inner.extend(streams);
249 }
250}
251
252impl Extend<TokenStream> for TokenStream {
253 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
254 self.inner
255 .extend(streams.into_iter().map(|stream| stream.inner));
256 }
257}
258
259/// Collects a number of token trees into a single stream.
260impl FromIterator<TokenTree> for TokenStream {
261 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
262 TokenStream::_new(streams.into_iter().collect())
263 }
264}
265impl FromIterator<TokenStream> for TokenStream {
266 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
267 TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
268 }
269}
270
271/// Prints the token stream as a string that is supposed to be losslessly
272/// convertible back into the same token stream (modulo spans), except for
273/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
274/// numeric literals.
275impl Display for TokenStream {
276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
277 Display::fmt(&self.inner, f)
278 }
279}
280
281/// Prints token in a form convenient for debugging.
282impl Debug for TokenStream {
283 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
284 Debug::fmt(&self.inner, f)
285 }
286}
287
288impl LexError {
289 pub fn span(&self) -> Span {
290 Span::_new(self.inner.span())
291 }
292}
293
294impl Debug for LexError {
295 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
296 Debug::fmt(&self.inner, f)
297 }
298}
299
300impl Display for LexError {
301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
302 Display::fmt(&self.inner, f)
303 }
304}
305
306impl Error for LexError {}
307
308/// The source file of a given `Span`.
309///
310/// This type is semver exempt and not exposed by default.
311#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
312#[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))]
313#[derive(Clone, PartialEq, Eq)]
314pub struct SourceFile {
315 inner: imp::SourceFile,
316 _marker: Marker,
317}
318
319#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
320impl SourceFile {
321 fn _new(inner: imp::SourceFile) -> Self {
322 SourceFile {
323 inner,
324 _marker: Marker,
325 }
326 }
327
328 /// Get the path to this source file.
329 ///
330 /// ### Note
331 ///
332 /// If the code span associated with this `SourceFile` was generated by an
333 /// external macro, this may not be an actual path on the filesystem. Use
334 /// [`is_real`] to check.
335 ///
336 /// Also note that even if `is_real` returns `true`, if
337 /// `--remap-path-prefix` was passed on the command line, the path as given
338 /// may not actually be valid.
339 ///
340 /// [`is_real`]: #method.is_real
341 pub fn path(&self) -> PathBuf {
342 self.inner.path()
343 }
344
345 /// Returns `true` if this source file is a real source file, and not
346 /// generated by an external macro's expansion.
347 pub fn is_real(&self) -> bool {
348 self.inner.is_real()
349 }
350}
351
352#[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
353impl Debug for SourceFile {
354 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
355 Debug::fmt(&self.inner, f)
356 }
357}
358
359/// A line-column pair representing the start or end of a `Span`.
360///
361/// This type is semver exempt and not exposed by default.
362#[cfg(span_locations)]
363#[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))]
364#[derive(Copy, Clone, Debug, PartialEq, Eq)]
365pub struct LineColumn {
366 /// The 1-indexed line in the source file on which the span starts or ends
367 /// (inclusive).
368 pub line: usize,
369 /// The 0-indexed column (in UTF-8 characters) in the source file on which
370 /// the span starts or ends (inclusive).
371 pub column: usize,
372}
373
374#[cfg(span_locations)]
375impl Ord for LineColumn {
376 fn cmp(&self, other: &Self) -> Ordering {
377 self.line
378 .cmp(&other.line)
379 .then(self.column.cmp(&other.column))
380 }
381}
382
383#[cfg(span_locations)]
384impl PartialOrd for LineColumn {
385 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
386 Some(self.cmp(other))
387 }
388}
389
390/// A region of source code, along with macro expansion information.
391#[derive(Copy, Clone)]
392pub struct Span {
393 inner: imp::Span,
394 _marker: Marker,
395}
396
397impl Span {
398 fn _new(inner: imp::Span) -> Self {
399 Span {
400 inner,
401 _marker: Marker,
402 }
403 }
404
405 fn _new_stable(inner: fallback::Span) -> Self {
406 Span {
407 inner: inner.into(),
408 _marker: Marker,
409 }
410 }
411
412 /// The span of the invocation of the current procedural macro.
413 ///
414 /// Identifiers created with this span will be resolved as if they were
415 /// written directly at the macro call location (call-site hygiene) and
416 /// other code at the macro call site will be able to refer to them as well.
417 pub fn call_site() -> Self {
418 Span::_new(imp::Span::call_site())
419 }
420
421 /// The span located at the invocation of the procedural macro, but with
422 /// local variables, labels, and `$crate` resolved at the definition site
423 /// of the macro. This is the same hygiene behavior as `macro_rules`.
424 ///
425 /// This function requires Rust 1.45 or later.
426 #[cfg(not(no_hygiene))]
427 pub fn mixed_site() -> Self {
428 Span::_new(imp::Span::mixed_site())
429 }
430
431 /// A span that resolves at the macro definition site.
432 ///
433 /// This method is semver exempt and not exposed by default.
434 #[cfg(procmacro2_semver_exempt)]
435 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))]
436 pub fn def_site() -> Self {
437 Span::_new(imp::Span::def_site())
438 }
439
440 /// Creates a new span with the same line/column information as `self` but
441 /// that resolves symbols as though it were at `other`.
442 pub fn resolved_at(&self, other: Span) -> Span {
443 Span::_new(self.inner.resolved_at(other.inner))
444 }
445
446 /// Creates a new span with the same name resolution behavior as `self` but
447 /// with the line/column information of `other`.
448 pub fn located_at(&self, other: Span) -> Span {
449 Span::_new(self.inner.located_at(other.inner))
450 }
451
452 /// Convert `proc_macro2::Span` to `proc_macro::Span`.
453 ///
454 /// This method is available when building with a nightly compiler, or when
455 /// building with rustc 1.29+ *without* semver exempt features.
456 ///
457 /// # Panics
458 ///
459 /// Panics if called from outside of a procedural macro. Unlike
460 /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
461 /// the context of a procedural macro invocation.
462 #[cfg(wrap_proc_macro)]
463 pub fn unwrap(self) -> proc_macro::Span {
464 self.inner.unwrap()
465 }
466
467 // Soft deprecated. Please use Span::unwrap.
468 #[cfg(wrap_proc_macro)]
469 #[doc(hidden)]
470 pub fn unstable(self) -> proc_macro::Span {
471 self.unwrap()
472 }
473
474 /// The original source file into which this span points.
475 ///
476 /// This method is semver exempt and not exposed by default.
477 #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
478 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))]
479 pub fn source_file(&self) -> SourceFile {
480 SourceFile::_new(self.inner.source_file())
481 }
482
483 /// Get the starting line/column in the source file for this span.
484 ///
485 /// This method requires the `"span-locations"` feature to be enabled.
486 ///
487 /// When executing in a procedural macro context, the returned line/column
488 /// are only meaningful if compiled with a nightly toolchain. The stable
489 /// toolchain does not have this information available. When executing
490 /// outside of a procedural macro, such as main.rs or build.rs, the
491 /// line/column are always meaningful regardless of toolchain.
492 #[cfg(span_locations)]
493 #[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))]
494 pub fn start(&self) -> LineColumn {
495 let imp::LineColumn { line, column } = self.inner.start();
496 LineColumn { line, column }
497 }
498
499 /// Get the ending line/column in the source file for this span.
500 ///
501 /// This method requires the `"span-locations"` feature to be enabled.
502 ///
503 /// When executing in a procedural macro context, the returned line/column
504 /// are only meaningful if compiled with a nightly toolchain. The stable
505 /// toolchain does not have this information available. When executing
506 /// outside of a procedural macro, such as main.rs or build.rs, the
507 /// line/column are always meaningful regardless of toolchain.
508 #[cfg(span_locations)]
509 #[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))]
510 pub fn end(&self) -> LineColumn {
511 let imp::LineColumn { line, column } = self.inner.end();
512 LineColumn { line, column }
513 }
514
515 /// Creates an empty span pointing to directly before this span.
516 ///
517 /// This method is semver exempt and not exposed by default.
518 #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
519 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))]
520 pub fn before(&self) -> Span {
521 Span::_new(self.inner.before())
522 }
523
524 /// Creates an empty span pointing to directly after this span.
525 ///
526 /// This method is semver exempt and not exposed by default.
527 #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))]
528 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))]
529 pub fn after(&self) -> Span {
530 Span::_new(self.inner.after())
531 }
532
533 /// Create a new span encompassing `self` and `other`.
534 ///
535 /// Returns `None` if `self` and `other` are from different files.
536 ///
537 /// Warning: the underlying [`proc_macro::Span::join`] method is
538 /// nightly-only. When called from within a procedural macro not using a
539 /// nightly compiler, this method will always return `None`.
540 ///
541 /// [`proc_macro::Span::join`]: https://doc.rust-lang.org/proc_macro/struct.Span.html#method.join
542 pub fn join(&self, other: Span) -> Option<Span> {
543 self.inner.join(other.inner).map(Span::_new)
544 }
545
546 /// Compares two spans to see if they're equal.
547 ///
548 /// This method is semver exempt and not exposed by default.
549 #[cfg(procmacro2_semver_exempt)]
550 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))]
551 pub fn eq(&self, other: &Span) -> bool {
552 self.inner.eq(&other.inner)
553 }
554}
555
556/// Prints a span in a form convenient for debugging.
557impl Debug for Span {
558 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
559 Debug::fmt(&self.inner, f)
560 }
561}
562
563/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
564#[derive(Clone)]
565pub enum TokenTree {
566 /// A token stream surrounded by bracket delimiters.
567 Group(Group),
568 /// An identifier.
569 Ident(Ident),
570 /// A single punctuation character (`+`, `,`, `$`, etc.).
571 Punct(Punct),
572 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
573 Literal(Literal),
574}
575
576impl TokenTree {
577 /// Returns the span of this tree, delegating to the `span` method of
578 /// the contained token or a delimited stream.
579 pub fn span(&self) -> Span {
580 match self {
581 TokenTree::Group(t) => t.span(),
582 TokenTree::Ident(t) => t.span(),
583 TokenTree::Punct(t) => t.span(),
584 TokenTree::Literal(t) => t.span(),
585 }
586 }
587
588 /// Configures the span for *only this token*.
589 ///
590 /// Note that if this token is a `Group` then this method will not configure
591 /// the span of each of the internal tokens, this will simply delegate to
592 /// the `set_span` method of each variant.
593 pub fn set_span(&mut self, span: Span) {
594 match self {
595 TokenTree::Group(t) => t.set_span(span),
596 TokenTree::Ident(t) => t.set_span(span),
597 TokenTree::Punct(t) => t.set_span(span),
598 TokenTree::Literal(t) => t.set_span(span),
599 }
600 }
601}
602
603impl From<Group> for TokenTree {
604 fn from(g: Group) -> TokenTree {
605 TokenTree::Group(g)
606 }
607}
608
609impl From<Ident> for TokenTree {
610 fn from(g: Ident) -> TokenTree {
611 TokenTree::Ident(g)
612 }
613}
614
615impl From<Punct> for TokenTree {
616 fn from(g: Punct) -> TokenTree {
617 TokenTree::Punct(g)
618 }
619}
620
621impl From<Literal> for TokenTree {
622 fn from(g: Literal) -> TokenTree {
623 TokenTree::Literal(g)
624 }
625}
626
627/// Prints the token tree as a string that is supposed to be losslessly
628/// convertible back into the same token tree (modulo spans), except for
629/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
630/// numeric literals.
631impl Display for TokenTree {
632 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
633 match self {
634 TokenTree::Group(t) => Display::fmt(t, f),
635 TokenTree::Ident(t) => Display::fmt(t, f),
636 TokenTree::Punct(t) => Display::fmt(t, f),
637 TokenTree::Literal(t) => Display::fmt(t, f),
638 }
639 }
640}
641
642/// Prints token tree in a form convenient for debugging.
643impl Debug for TokenTree {
644 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
645 // Each of these has the name in the struct type in the derived debug,
646 // so don't bother with an extra layer of indirection
647 match self {
648 TokenTree::Group(t) => Debug::fmt(t, f),
649 TokenTree::Ident(t) => {
650 let mut debug = f.debug_struct("Ident");
651 debug.field("sym", &format_args!("{}", t));
652 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
653 debug.finish()
654 }
655 TokenTree::Punct(t) => Debug::fmt(t, f),
656 TokenTree::Literal(t) => Debug::fmt(t, f),
657 }
658 }
659}
660
661/// A delimited token stream.
662///
663/// A `Group` internally contains a `TokenStream` which is surrounded by
664/// `Delimiter`s.
665#[derive(Clone)]
666pub struct Group {
667 inner: imp::Group,
668}
669
670/// Describes how a sequence of token trees is delimited.
671#[derive(Copy, Clone, Debug, Eq, PartialEq)]
672pub enum Delimiter {
673 /// `( ... )`
674 Parenthesis,
675 /// `{ ... }`
676 Brace,
677 /// `[ ... ]`
678 Bracket,
679 /// `Ø ... Ø`
680 ///
681 /// An implicit delimiter, that may, for example, appear around tokens
682 /// coming from a "macro variable" `$var`. It is important to preserve
683 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
684 /// Implicit delimiters may not survive roundtrip of a token stream through
685 /// a string.
686 None,
687}
688
689impl Group {
690 fn _new(inner: imp::Group) -> Self {
691 Group { inner }
692 }
693
694 fn _new_stable(inner: fallback::Group) -> Self {
695 Group {
696 inner: inner.into(),
697 }
698 }
699
700 /// Creates a new `Group` with the given delimiter and token stream.
701 ///
702 /// This constructor will set the span for this group to
703 /// `Span::call_site()`. To change the span you can use the `set_span`
704 /// method below.
705 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
706 Group {
707 inner: imp::Group::new(delimiter, stream.inner),
708 }
709 }
710
711 /// Returns the delimiter of this `Group`
712 pub fn delimiter(&self) -> Delimiter {
713 self.inner.delimiter()
714 }
715
716 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
717 ///
718 /// Note that the returned token stream does not include the delimiter
719 /// returned above.
720 pub fn stream(&self) -> TokenStream {
721 TokenStream::_new(self.inner.stream())
722 }
723
724 /// Returns the span for the delimiters of this token stream, spanning the
725 /// entire `Group`.
726 ///
727 /// ```text
728 /// pub fn span(&self) -> Span {
729 /// ^^^^^^^
730 /// ```
731 pub fn span(&self) -> Span {
732 Span::_new(self.inner.span())
733 }
734
735 /// Returns the span pointing to the opening delimiter of this group.
736 ///
737 /// ```text
738 /// pub fn span_open(&self) -> Span {
739 /// ^
740 /// ```
741 pub fn span_open(&self) -> Span {
742 Span::_new(self.inner.span_open())
743 }
744
745 /// Returns the span pointing to the closing delimiter of this group.
746 ///
747 /// ```text
748 /// pub fn span_close(&self) -> Span {
749 /// ^
750 /// ```
751 pub fn span_close(&self) -> Span {
752 Span::_new(self.inner.span_close())
753 }
754
755 /// Configures the span for this `Group`'s delimiters, but not its internal
756 /// tokens.
757 ///
758 /// This method will **not** set the span of all the internal tokens spanned
759 /// by this group, but rather it will only set the span of the delimiter
760 /// tokens at the level of the `Group`.
761 pub fn set_span(&mut self, span: Span) {
762 self.inner.set_span(span.inner);
763 }
764}
765
766/// Prints the group as a string that should be losslessly convertible back
767/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
768/// with `Delimiter::None` delimiters.
769impl Display for Group {
770 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
771 Display::fmt(&self.inner, formatter)
772 }
773}
774
775impl Debug for Group {
776 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
777 Debug::fmt(&self.inner, formatter)
778 }
779}
780
781/// A `Punct` is a single punctuation character like `+`, `-` or `#`.
782///
783/// Multicharacter operators like `+=` are represented as two instances of
784/// `Punct` with different forms of `Spacing` returned.
785#[derive(Clone)]
786pub struct Punct {
787 ch: char,
788 spacing: Spacing,
789 span: Span,
790}
791
792/// Whether a `Punct` is followed immediately by another `Punct` or followed by
793/// another token or whitespace.
794#[derive(Copy, Clone, Debug, Eq, PartialEq)]
795pub enum Spacing {
796 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
797 Alone,
798 /// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.
799 ///
800 /// Additionally, single quote `'` can join with identifiers to form
801 /// lifetimes `'ident`.
802 Joint,
803}
804
805impl Punct {
806 /// Creates a new `Punct` from the given character and spacing.
807 ///
808 /// The `ch` argument must be a valid punctuation character permitted by the
809 /// language, otherwise the function will panic.
810 ///
811 /// The returned `Punct` will have the default span of `Span::call_site()`
812 /// which can be further configured with the `set_span` method below.
813 pub fn new(ch: char, spacing: Spacing) -> Self {
814 Punct {
815 ch,
816 spacing,
817 span: Span::call_site(),
818 }
819 }
820
821 /// Returns the value of this punctuation character as `char`.
822 pub fn as_char(&self) -> char {
823 self.ch
824 }
825
826 /// Returns the spacing of this punctuation character, indicating whether
827 /// it's immediately followed by another `Punct` in the token stream, so
828 /// they can potentially be combined into a multicharacter operator
829 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
830 /// so the operator has certainly ended.
831 pub fn spacing(&self) -> Spacing {
832 self.spacing
833 }
834
835 /// Returns the span for this punctuation character.
836 pub fn span(&self) -> Span {
837 self.span
838 }
839
840 /// Configure the span for this punctuation character.
841 pub fn set_span(&mut self, span: Span) {
842 self.span = span;
843 }
844}
845
846/// Prints the punctuation character as a string that should be losslessly
847/// convertible back into the same character.
848impl Display for Punct {
849 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
850 Display::fmt(&self.ch, f)
851 }
852}
853
854impl Debug for Punct {
855 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
856 let mut debug = fmt.debug_struct("Punct");
857 debug.field("char", &self.ch);
858 debug.field("spacing", &self.spacing);
859 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
860 debug.finish()
861 }
862}
863
864/// A word of Rust code, which may be a keyword or legal variable name.
865///
866/// An identifier consists of at least one Unicode code point, the first of
867/// which has the XID_Start property and the rest of which have the XID_Continue
868/// property.
869///
870/// - The empty string is not an identifier. Use `Option<Ident>`.
871/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
872///
873/// An identifier constructed with `Ident::new` is permitted to be a Rust
874/// keyword, though parsing one through its [`Parse`] implementation rejects
875/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
876/// behaviour of `Ident::new`.
877///
878/// [`Parse`]: https://docs.rs/syn/1.0/syn/parse/trait.Parse.html
879///
880/// # Examples
881///
882/// A new ident can be created from a string using the `Ident::new` function.
883/// A span must be provided explicitly which governs the name resolution
884/// behavior of the resulting identifier.
885///
886/// ```
887/// use proc_macro2::{Ident, Span};
888///
889/// fn main() {
890/// let call_ident = Ident::new("calligraphy", Span::call_site());
891///
892/// println!("{}", call_ident);
893/// }
894/// ```
895///
896/// An ident can be interpolated into a token stream using the `quote!` macro.
897///
898/// ```
899/// use proc_macro2::{Ident, Span};
900/// use quote::quote;
901///
902/// fn main() {
903/// let ident = Ident::new("demo", Span::call_site());
904///
905/// // Create a variable binding whose name is this ident.
906/// let expanded = quote! { let #ident = 10; };
907///
908/// // Create a variable binding with a slightly different name.
909/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
910/// let expanded = quote! { let #temp_ident = 10; };
911/// }
912/// ```
913///
914/// A string representation of the ident is available through the `to_string()`
915/// method.
916///
917/// ```
918/// # use proc_macro2::{Ident, Span};
919/// #
920/// # let ident = Ident::new("another_identifier", Span::call_site());
921/// #
922/// // Examine the ident as a string.
923/// let ident_string = ident.to_string();
924/// if ident_string.len() > 60 {
925/// println!("Very long identifier: {}", ident_string)
926/// }
927/// ```
928#[derive(Clone)]
929pub struct Ident {
930 inner: imp::Ident,
931 _marker: Marker,
932}
933
934impl Ident {
935 fn _new(inner: imp::Ident) -> Self {
936 Ident {
937 inner,
938 _marker: Marker,
939 }
940 }
941
942 /// Creates a new `Ident` with the given `string` as well as the specified
943 /// `span`.
944 ///
945 /// The `string` argument must be a valid identifier permitted by the
946 /// language, otherwise the function will panic.
947 ///
948 /// Note that `span`, currently in rustc, configures the hygiene information
949 /// for this identifier.
950 ///
951 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
952 /// hygiene meaning that identifiers created with this span will be resolved
953 /// as if they were written directly at the location of the macro call, and
954 /// other code at the macro call site will be able to refer to them as well.
955 ///
956 /// Later spans like `Span::def_site()` will allow to opt-in to
957 /// "definition-site" hygiene meaning that identifiers created with this
958 /// span will be resolved at the location of the macro definition and other
959 /// code at the macro call site will not be able to refer to them.
960 ///
961 /// Due to the current importance of hygiene this constructor, unlike other
962 /// tokens, requires a `Span` to be specified at construction.
963 ///
964 /// # Panics
965 ///
966 /// Panics if the input string is neither a keyword nor a legal variable
967 /// name. If you are not sure whether the string contains an identifier and
968 /// need to handle an error case, use
969 /// <a href="https://docs.rs/syn/1.0/syn/fn.parse_str.html"><code
970 /// style="padding-right:0;">syn::parse_str</code></a><code
971 /// style="padding-left:0;">::<Ident></code>
972 /// rather than `Ident::new`.
973 pub fn new(string: &str, span: Span) -> Self {
974 Ident::_new(imp::Ident::new(string, span.inner))
975 }
976
977 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The
978 /// `string` argument must be a valid identifier permitted by the language
979 /// (including keywords, e.g. `fn`). Keywords which are usable in path
980 /// segments (e.g. `self`, `super`) are not supported, and will cause a
981 /// panic.
982 pub fn new_raw(string: &str, span: Span) -> Self {
983 Ident::_new_raw(string, span)
984 }
985
986 fn _new_raw(string: &str, span: Span) -> Self {
987 Ident::_new(imp::Ident::new_raw(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: Marker,
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_stable(inner: fallback::Literal) -> Self {
1112 Literal {
1113 inner: inner.into(),
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 string literal.
1231 pub fn byte_string(s: &[u8]) -> Literal {
1232 Literal::_new(imp::Literal::byte_string(s))
1233 }
1234
1235 /// Returns the span encompassing this literal.
1236 pub fn span(&self) -> Span {
1237 Span::_new(self.inner.span())
1238 }
1239
1240 /// Configures the span associated for this literal.
1241 pub fn set_span(&mut self, span: Span) {
1242 self.inner.set_span(span.inner);
1243 }
1244
1245 /// Returns a `Span` that is a subset of `self.span()` containing only
1246 /// the source bytes in range `range`. Returns `None` if the would-be
1247 /// trimmed span is outside the bounds of `self`.
1248 ///
1249 /// Warning: the underlying [`proc_macro::Literal::subspan`] method is
1250 /// nightly-only. When called from within a procedural macro not using a
1251 /// nightly compiler, this method will always return `None`.
1252 ///
1253 /// [`proc_macro::Literal::subspan`]: https://doc.rust-lang.org/proc_macro/struct.Literal.html#method.subspan
1254 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1255 self.inner.subspan(range).map(Span::_new)
1256 }
1257
1258 // Intended for the `quote!` macro to use when constructing a proc-macro2
1259 // token out of a macro_rules $:literal token, which is already known to be
1260 // a valid literal. This avoids reparsing/validating the literal's string
1261 // representation. This is not public API other than for quote.
1262 #[doc(hidden)]
1263 pub unsafe fn from_str_unchecked(repr: &str) -> Self {
1264 Literal::_new(imp::Literal::from_str_unchecked(repr))
1265 }
1266}
1267
1268impl FromStr for Literal {
1269 type Err = LexError;
1270
1271 fn from_str(repr: &str) -> Result<Self, LexError> {
1272 repr.parse().map(Literal::_new).map_err(|inner| LexError {
1273 inner,
1274 _marker: Marker,
1275 })
1276 }
1277}
1278
1279impl Debug for Literal {
1280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1281 Debug::fmt(&self.inner, f)
1282 }
1283}
1284
1285impl Display for Literal {
1286 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1287 Display::fmt(&self.inner, f)
1288 }
1289}
1290
1291/// Public implementation details for the `TokenStream` type, such as iterators.
1292pub mod token_stream {
1293 use crate::marker::Marker;
1294 use crate::{imp, TokenTree};
1295 use core::fmt::{self, Debug};
1296
1297 pub use crate::TokenStream;
1298
1299 /// An iterator over `TokenStream`'s `TokenTree`s.
1300 ///
1301 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1302 /// delimited groups, and returns whole groups as token trees.
1303 #[derive(Clone)]
1304 pub struct IntoIter {
1305 inner: imp::TokenTreeIter,
1306 _marker: Marker,
1307 }
1308
1309 impl Iterator for IntoIter {
1310 type Item = TokenTree;
1311
1312 fn next(&mut self) -> Option<TokenTree> {
1313 self.inner.next()
1314 }
1315
1316 fn size_hint(&self) -> (usize, Option<usize>) {
1317 self.inner.size_hint()
1318 }
1319 }
1320
1321 impl Debug for IntoIter {
1322 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1323 f.write_str("TokenStream ")?;
1324 f.debug_list().entries(self.clone()).finish()
1325 }
1326 }
1327
1328 impl IntoIterator for TokenStream {
1329 type Item = TokenTree;
1330 type IntoIter = IntoIter;
1331
1332 fn into_iter(self) -> IntoIter {
1333 IntoIter {
1334 inner: self.inner.into_iter(),
1335 _marker: Marker,
1336 }
1337 }
1338 }
1339}