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