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