Skip to main content

proc_macro/
lib.rs

1//! A support library for macro authors when defining new macros.
2//!
3//! This library, provided by the standard distribution, provides the types
4//! consumed in the interfaces of procedurally defined macro definitions such as
5//! function-like macros `#[proc_macro]`, macro attributes `#[proc_macro_attribute]` and
6//! custom derive attributes `#[proc_macro_derive]`.
7//!
8//! See [the book] for more.
9//!
10//! [the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes
11
12#![stable(feature = "proc_macro_lib", since = "1.15.0")]
13#![deny(missing_docs)]
14#![doc(
15    html_playground_url = "https://play.rust-lang.org/",
16    issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
17    test(no_crate_inject, attr(deny(warnings))),
18    test(attr(allow(dead_code, deprecated, unused_variables, unused_mut)))
19)]
20#![doc(rust_logo)]
21#![feature(rustdoc_internals)]
22#![feature(staged_api)]
23#![feature(allow_internal_unstable)]
24#![feature(decl_macro)]
25#![feature(negative_impls)]
26#![feature(panic_can_unwind)]
27#![feature(restricted_std)]
28#![feature(rustc_attrs)]
29#![feature(extend_one)]
30#![feature(mem_conjure_zst)]
31#![feature(f16)]
32#![recursion_limit = "256"]
33#![allow(internal_features)]
34#![deny(ffi_unwind_calls)]
35#![allow(rustc::internal)] // Can't use FxHashMap when compiled as part of the standard library
36#![warn(rustdoc::unescaped_backticks)]
37#![warn(unreachable_pub)]
38#![deny(unsafe_op_in_unsafe_fn)]
39
40#[unstable(feature = "proc_macro_internals", issue = "27812")]
41#[doc(hidden)]
42pub mod bridge;
43
44mod diagnostic;
45mod escape;
46mod to_tokens;
47
48use core::convert::From;
49use core::ops::BitOr;
50use std::borrow::Cow;
51use std::ffi::CStr;
52use std::ops::{Range, RangeBounds};
53use std::path::PathBuf;
54use std::str::FromStr;
55use std::{error, fmt};
56
57#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
58pub use diagnostic::{Diagnostic, Level, MultiSpan};
59use rustc_literal_escaper::{
60    MixedUnit, unescape_byte, unescape_byte_str, unescape_c_str, unescape_char, unescape_str,
61};
62#[unstable(feature = "proc_macro_totokens", issue = "130977")]
63pub use to_tokens::ToTokens;
64
65use crate::bridge::client::Methods as BridgeMethods;
66use crate::escape::{EscapeOptions, escape_bytes};
67
68/// Mostly relating to malformed escape sequences, but also a few other problems.
69#[unstable(feature = "proc_macro_value", issue = "136652")]
70#[derive(Debug, PartialEq, Eq)]
71#[non_exhaustive]
72pub enum EscapeError {
73    /// Expected 1 char, but 0 were found.
74    ZeroChars,
75    /// Expected 1 char, but more than 1 were found.
76    MoreThanOneChar,
77
78    /// Escaped '\' character without continuation.
79    LoneSlash,
80    /// Invalid escape character (e.g. '\z').
81    InvalidEscape,
82    /// Raw '\r' encountered.
83    BareCarriageReturn,
84    /// Raw '\r' encountered in raw string.
85    BareCarriageReturnInRawString,
86    /// Unescaped character that was expected to be escaped (e.g. raw '\t').
87    EscapeOnlyChar,
88
89    /// Numeric character escape is too short (e.g. '\x1').
90    TooShortHexEscape,
91    /// Invalid character in numeric escape (e.g. '\xz')
92    InvalidCharInHexEscape,
93    /// Character code in numeric escape is non-ascii (e.g. '\xFF').
94    OutOfRangeHexEscape,
95
96    /// '\u' not followed by '{'.
97    NoBraceInUnicodeEscape,
98    /// Non-hexadecimal value in '\u{..}'.
99    InvalidCharInUnicodeEscape,
100    /// '\u{}'
101    EmptyUnicodeEscape,
102    /// No closing brace in '\u{..}', e.g. '\u{12'.
103    UnclosedUnicodeEscape,
104    /// '\u{_12}'
105    LeadingUnderscoreUnicodeEscape,
106    /// More than 6 characters in '\u{..}', e.g. '\u{10FFFF_FF}'
107    OverlongUnicodeEscape,
108    /// Invalid in-bound unicode character code, e.g. '\u{DFFF}'.
109    LoneSurrogateUnicodeEscape,
110    /// Out of bounds unicode character code, e.g. '\u{FFFFFF}'.
111    OutOfRangeUnicodeEscape,
112
113    /// Unicode escape code in byte literal.
114    UnicodeEscapeInByte,
115    /// Non-ascii character in byte literal, byte string literal, or raw byte string literal.
116    NonAsciiCharInByte,
117
118    /// `\0` in a C string literal.
119    NulInCStr,
120
121    /// After a line ending with '\', the next line contains whitespace
122    /// characters that are not skipped.
123    UnskippedWhitespaceWarning,
124
125    /// After a line ending with '\', multiple lines are skipped.
126    MultipleSkippedLinesWarning,
127}
128
129#[unstable(feature = "proc_macro_value", issue = "136652")]
130#[doc(hidden)]
131impl From<rustc_literal_escaper::EscapeError> for EscapeError {
132    fn from(value: rustc_literal_escaper::EscapeError) -> Self {
133        use rustc_literal_escaper::EscapeError as EE;
134
135        match value {
136            EE::ZeroChars => Self::ZeroChars,
137            EE::MoreThanOneChar => Self::MoreThanOneChar,
138            EE::LoneSlash => Self::LoneSlash,
139            EE::InvalidEscape => Self::InvalidEscape,
140            EE::BareCarriageReturn => Self::BareCarriageReturn,
141            EE::BareCarriageReturnInRawString => Self::BareCarriageReturnInRawString,
142            EE::EscapeOnlyChar => Self::EscapeOnlyChar,
143            EE::TooShortHexEscape => Self::TooShortHexEscape,
144            EE::InvalidCharInHexEscape => Self::InvalidCharInHexEscape,
145            EE::OutOfRangeHexEscape => Self::OutOfRangeHexEscape,
146            EE::NoBraceInUnicodeEscape => Self::NoBraceInUnicodeEscape,
147            EE::InvalidCharInUnicodeEscape => Self::InvalidCharInUnicodeEscape,
148            EE::EmptyUnicodeEscape => Self::EmptyUnicodeEscape,
149            EE::UnclosedUnicodeEscape => Self::UnclosedUnicodeEscape,
150            EE::LeadingUnderscoreUnicodeEscape => Self::LeadingUnderscoreUnicodeEscape,
151            EE::OverlongUnicodeEscape => Self::OverlongUnicodeEscape,
152            EE::LoneSurrogateUnicodeEscape => Self::LoneSurrogateUnicodeEscape,
153            EE::OutOfRangeUnicodeEscape => Self::OutOfRangeUnicodeEscape,
154            EE::UnicodeEscapeInByte => Self::UnicodeEscapeInByte,
155            EE::NonAsciiCharInByte => Self::NonAsciiCharInByte,
156            EE::NulInCStr => Self::NulInCStr,
157            EE::UnskippedWhitespaceWarning => Self::UnskippedWhitespaceWarning,
158            EE::MultipleSkippedLinesWarning => Self::MultipleSkippedLinesWarning,
159        }
160    }
161}
162
163#[unstable(feature = "proc_macro_value", issue = "136652")]
164impl error::Error for EscapeError {}
165
166#[unstable(feature = "proc_macro_value", issue = "136652")]
167impl fmt::Display for EscapeError {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        f.write_str(match self {
170            Self::ZeroChars => "zero chars",
171            Self::MoreThanOneChar => "more than one char",
172            Self::LoneSlash => "lone slash",
173            Self::InvalidEscape => "invalid escape",
174            Self::BareCarriageReturn => "bare carriage return",
175            Self::BareCarriageReturnInRawString => "bare carriage return in raw string",
176            Self::EscapeOnlyChar => "escape only char",
177            Self::TooShortHexEscape => "too short hex escape",
178            Self::InvalidCharInHexEscape => "invalid char in hex escape",
179            Self::OutOfRangeHexEscape => "out of range hex escape",
180            Self::NoBraceInUnicodeEscape => "no brace in unicode escape",
181            Self::InvalidCharInUnicodeEscape => "invalid char in unicode escape",
182            Self::EmptyUnicodeEscape => "empty unicode escape",
183            Self::UnclosedUnicodeEscape => "unclosed unicode escape",
184            Self::LeadingUnderscoreUnicodeEscape => "leading underscore unicode escape",
185            Self::OverlongUnicodeEscape => "overlong unicode escape",
186            Self::LoneSurrogateUnicodeEscape => "lone surrogate unicode escape",
187            Self::OutOfRangeUnicodeEscape => "out of range unicode escape",
188            Self::UnicodeEscapeInByte => "unicode escape in byte",
189            Self::NonAsciiCharInByte => "non ascii char in byte",
190            Self::NulInCStr => "nul in CStr",
191            Self::UnskippedWhitespaceWarning => "unskipped whitespace warning",
192            Self::MultipleSkippedLinesWarning => "multiple skipped lines warning",
193        })
194    }
195}
196
197/// Errors returned when trying to retrieve a literal unescaped value.
198#[unstable(feature = "proc_macro_value", issue = "136652")]
199#[derive(Debug, PartialEq, Eq)]
200pub enum ConversionErrorKind {
201    /// The literal failed to be escaped, take a look at [`EscapeError`] for more information.
202    FailedToUnescape(EscapeError),
203    /// Trying to convert a literal with the wrong type.
204    InvalidLiteralKind,
205}
206
207/// Determines whether proc_macro has been made accessible to the currently
208/// running program.
209///
210/// The proc_macro crate is only intended for use inside the implementation of
211/// procedural macros. All the functions in this crate panic if invoked from
212/// outside of a procedural macro, such as from a build script or unit test or
213/// ordinary Rust binary.
214///
215/// With consideration for Rust libraries that are designed to support both
216/// macro and non-macro use cases, `proc_macro::is_available()` provides a
217/// non-panicking way to detect whether the infrastructure required to use the
218/// API of proc_macro is presently available. Returns true if invoked from
219/// inside of a procedural macro, false if invoked from any other binary.
220#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
221pub fn is_available() -> bool {
222    bridge::client::is_available()
223}
224
225/// The main type provided by this crate, representing an abstract stream of
226/// tokens, or, more specifically, a sequence of token trees.
227/// The type provides interfaces for iterating over those token trees and, conversely,
228/// collecting a number of token trees into one stream.
229///
230/// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
231/// and `#[proc_macro_derive]` definitions.
232#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
233#[stable(feature = "proc_macro_lib", since = "1.15.0")]
234#[derive(Clone)]
235pub struct TokenStream(Option<bridge::client::TokenStream>);
236
237#[stable(feature = "proc_macro_lib", since = "1.15.0")]
238impl !Send for TokenStream {}
239#[stable(feature = "proc_macro_lib", since = "1.15.0")]
240impl !Sync for TokenStream {}
241
242/// Error returned from `TokenStream::from_str`.
243///
244/// The contained error message is explicitly not guaranteed to be stable in any way,
245/// and may change between Rust versions or across compilations.
246#[stable(feature = "proc_macro_lib", since = "1.15.0")]
247#[non_exhaustive]
248#[derive(Debug)]
249pub struct LexError(String);
250
251#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
252impl fmt::Display for LexError {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        f.write_str(&self.0)
255    }
256}
257
258#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
259impl error::Error for LexError {}
260
261#[stable(feature = "proc_macro_lib", since = "1.15.0")]
262impl !Send for LexError {}
263#[stable(feature = "proc_macro_lib", since = "1.15.0")]
264impl !Sync for LexError {}
265
266/// Error returned from `TokenStream::expand_expr`.
267#[unstable(feature = "proc_macro_expand", issue = "90765")]
268#[non_exhaustive]
269#[derive(Debug)]
270pub struct ExpandError;
271
272#[unstable(feature = "proc_macro_expand", issue = "90765")]
273impl fmt::Display for ExpandError {
274    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275        f.write_str("macro expansion failed")
276    }
277}
278
279#[unstable(feature = "proc_macro_expand", issue = "90765")]
280impl error::Error for ExpandError {}
281
282#[unstable(feature = "proc_macro_expand", issue = "90765")]
283impl !Send for ExpandError {}
284
285#[unstable(feature = "proc_macro_expand", issue = "90765")]
286impl !Sync for ExpandError {}
287
288impl TokenStream {
289    /// Returns an empty `TokenStream` containing no token trees.
290    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
291    pub fn new() -> TokenStream {
292        TokenStream(None)
293    }
294
295    /// Checks if this `TokenStream` is empty.
296    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
297    pub fn is_empty(&self) -> bool {
298        self.0.as_ref().map(|h| BridgeMethods::ts_is_empty(h)).unwrap_or(true)
299    }
300
301    /// Parses this `TokenStream` as an expression and attempts to expand any
302    /// macros within it. Returns the expanded `TokenStream`.
303    ///
304    /// Currently only expressions expanding to literals will succeed, although
305    /// this may be relaxed in the future.
306    ///
307    /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
308    /// report an error, failing compilation, and/or return an `Err(..)`. The
309    /// specific behavior for any error condition, and what conditions are
310    /// considered errors, is unspecified and may change in the future.
311    #[unstable(feature = "proc_macro_expand", issue = "90765")]
312    pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
313        let stream = self.0.as_ref().ok_or(ExpandError)?;
314        match BridgeMethods::ts_expand_expr(stream) {
315            Ok(stream) => Ok(TokenStream(Some(stream))),
316            Err(_) => Err(ExpandError),
317        }
318    }
319}
320
321/// Attempts to break the string into tokens and parse those tokens into a token stream.
322/// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
323/// or characters not existing in the language.
324/// All tokens in the parsed stream get `Span::call_site()` spans.
325///
326/// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
327/// change these errors into `LexError`s later.
328#[stable(feature = "proc_macro_lib", since = "1.15.0")]
329impl FromStr for TokenStream {
330    type Err = LexError;
331
332    fn from_str(src: &str) -> Result<TokenStream, LexError> {
333        Ok(TokenStream(Some(BridgeMethods::ts_from_str(src).map_err(LexError)?)))
334    }
335}
336
337/// Prints the token stream as a string that is supposed to be losslessly convertible back
338/// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
339/// with `Delimiter::None` delimiters and negative numeric literals.
340///
341/// Note: the exact form of the output is subject to change, e.g. there might
342/// be changes in the whitespace used between tokens. Therefore, you should
343/// *not* do any kind of simple substring matching on the output string (as
344/// produced by `to_string`) to implement a proc macro, because that matching
345/// might stop working if such changes happen. Instead, you should work at the
346/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
347/// `TokenTree::Punct`, or `TokenTree::Literal`.
348#[stable(feature = "proc_macro_lib", since = "1.15.0")]
349impl fmt::Display for TokenStream {
350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351        match &self.0 {
352            Some(ts) => write!(f, "{}", BridgeMethods::ts_to_string(ts)),
353            None => Ok(()),
354        }
355    }
356}
357
358/// Prints tokens in a form convenient for debugging.
359#[stable(feature = "proc_macro_lib", since = "1.15.0")]
360impl fmt::Debug for TokenStream {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        f.write_str("TokenStream ")?;
363        f.debug_list().entries(self.clone()).finish()
364    }
365}
366
367#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
368impl Default for TokenStream {
369    fn default() -> Self {
370        TokenStream::new()
371    }
372}
373
374#[unstable(feature = "proc_macro_quote", issue = "54722")]
375pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
376
377fn tree_to_bridge_tree(
378    tree: TokenTree,
379) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
380    match tree {
381        TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
382        TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
383        TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
384        TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
385    }
386}
387
388/// Creates a token stream containing a single token tree.
389#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
390impl From<TokenTree> for TokenStream {
391    fn from(tree: TokenTree) -> TokenStream {
392        TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
393    }
394}
395
396/// Non-generic helper for implementing `FromIterator<TokenTree>` and
397/// `Extend<TokenTree>` with less monomorphization in calling crates.
398struct ConcatTreesHelper {
399    trees: Vec<
400        bridge::TokenTree<
401            bridge::client::TokenStream,
402            bridge::client::Span,
403            bridge::client::Symbol,
404        >,
405    >,
406}
407
408impl ConcatTreesHelper {
409    fn new(capacity: usize) -> Self {
410        ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
411    }
412
413    fn push(&mut self, tree: TokenTree) {
414        self.trees.push(tree_to_bridge_tree(tree));
415    }
416
417    fn build(self) -> TokenStream {
418        if self.trees.is_empty() {
419            TokenStream(None)
420        } else {
421            TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
422        }
423    }
424
425    fn append_to(self, stream: &mut TokenStream) {
426        if self.trees.is_empty() {
427            return;
428        }
429        stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
430    }
431}
432
433/// Non-generic helper for implementing `FromIterator<TokenStream>` and
434/// `Extend<TokenStream>` with less monomorphization in calling crates.
435struct ConcatStreamsHelper {
436    streams: Vec<bridge::client::TokenStream>,
437}
438
439impl ConcatStreamsHelper {
440    fn new(capacity: usize) -> Self {
441        ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
442    }
443
444    fn push(&mut self, stream: TokenStream) {
445        if let Some(stream) = stream.0 {
446            self.streams.push(stream);
447        }
448    }
449
450    fn build(mut self) -> TokenStream {
451        if self.streams.len() <= 1 {
452            TokenStream(self.streams.pop())
453        } else {
454            TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
455        }
456    }
457
458    fn append_to(mut self, stream: &mut TokenStream) {
459        if self.streams.is_empty() {
460            return;
461        }
462        let base = stream.0.take();
463        if base.is_none() && self.streams.len() == 1 {
464            stream.0 = self.streams.pop();
465        } else {
466            stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
467        }
468    }
469}
470
471/// Collects a number of token trees into a single stream.
472#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
473impl FromIterator<TokenTree> for TokenStream {
474    fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
475        let iter = trees.into_iter();
476        let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
477        iter.for_each(|tree| builder.push(tree));
478        builder.build()
479    }
480}
481
482/// A "flattening" operation on token streams, collects token trees
483/// from multiple token streams into a single stream.
484#[stable(feature = "proc_macro_lib", since = "1.15.0")]
485impl FromIterator<TokenStream> for TokenStream {
486    fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
487        let iter = streams.into_iter();
488        let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
489        iter.for_each(|stream| builder.push(stream));
490        builder.build()
491    }
492}
493
494#[stable(feature = "token_stream_extend", since = "1.30.0")]
495impl Extend<TokenTree> for TokenStream {
496    fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
497        let iter = trees.into_iter();
498        let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
499        iter.for_each(|tree| builder.push(tree));
500        builder.append_to(self);
501    }
502}
503
504#[stable(feature = "token_stream_extend", since = "1.30.0")]
505impl Extend<TokenStream> for TokenStream {
506    fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
507        let iter = streams.into_iter();
508        let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
509        iter.for_each(|stream| builder.push(stream));
510        builder.append_to(self);
511    }
512}
513
514macro_rules! extend_items {
515    ($($item:ident)*) => {
516        $(
517            #[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
518            impl Extend<$item> for TokenStream {
519                fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
520                    self.extend(iter.into_iter().map(TokenTree::$item));
521                }
522            }
523        )*
524    };
525}
526
527extend_items!(Group Literal Punct Ident);
528
529/// Public implementation details for the `TokenStream` type, such as iterators.
530#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
531pub mod token_stream {
532    use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
533
534    /// An iterator over `TokenStream`'s `TokenTree`s.
535    /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
536    /// and returns whole groups as token trees.
537    #[derive(Clone)]
538    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
539    pub struct IntoIter(
540        std::vec::IntoIter<
541            bridge::TokenTree<
542                bridge::client::TokenStream,
543                bridge::client::Span,
544                bridge::client::Symbol,
545            >,
546        >,
547    );
548
549    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
550    impl Iterator for IntoIter {
551        type Item = TokenTree;
552
553        fn next(&mut self) -> Option<TokenTree> {
554            self.0.next().map(|tree| match tree {
555                bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
556                bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
557                bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
558                bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
559            })
560        }
561
562        fn size_hint(&self) -> (usize, Option<usize>) {
563            self.0.size_hint()
564        }
565
566        fn count(self) -> usize {
567            self.0.count()
568        }
569    }
570
571    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
572    impl IntoIterator for TokenStream {
573        type Item = TokenTree;
574        type IntoIter = IntoIter;
575
576        fn into_iter(self) -> IntoIter {
577            IntoIter(
578                self.0.map(|v| BridgeMethods::ts_into_trees(v)).unwrap_or_default().into_iter(),
579            )
580        }
581    }
582}
583
584/// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
585/// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
586/// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
587///
588/// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
589/// To quote `$` itself, use `$$`.
590#[unstable(feature = "proc_macro_quote", issue = "54722")]
591#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
592#[rustc_builtin_macro]
593pub macro quote($($t:tt)*) {
594    /* compiler built-in */
595}
596
597#[unstable(feature = "proc_macro_internals", issue = "27812")]
598#[doc(hidden)]
599mod quote;
600
601/// A region of source code, along with macro expansion information.
602#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
603#[derive(Copy, Clone)]
604pub struct Span(bridge::client::Span);
605
606#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
607impl !Send for Span {}
608#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
609impl !Sync for Span {}
610
611macro_rules! diagnostic_method {
612    ($name:ident, $level:expr) => {
613        /// Creates a new `Diagnostic` with the given `message` at the span
614        /// `self`.
615        #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
616        pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
617            Diagnostic::spanned(self, $level, message)
618        }
619    };
620}
621
622impl Span {
623    /// A span that resolves at the macro definition site.
624    #[unstable(feature = "proc_macro_def_site", issue = "54724")]
625    pub fn def_site() -> Span {
626        Span(bridge::client::Span::def_site())
627    }
628
629    /// The span of the invocation of the current procedural macro.
630    /// Identifiers created with this span will be resolved as if they were written
631    /// directly at the macro call location (call-site hygiene) and other code
632    /// at the macro call site will be able to refer to them as well.
633    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
634    pub fn call_site() -> Span {
635        Span(bridge::client::Span::call_site())
636    }
637
638    /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
639    /// definition site (local variables, labels, `$crate`) and sometimes at the macro
640    /// call site (everything else).
641    /// The span location is taken from the call-site.
642    #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
643    pub fn mixed_site() -> Span {
644        Span(bridge::client::Span::mixed_site())
645    }
646
647    /// The `Span` for the tokens in the previous macro expansion from which
648    /// `self` was generated from, if any.
649    #[unstable(feature = "proc_macro_span", issue = "54725")]
650    pub fn parent(&self) -> Option<Span> {
651        BridgeMethods::span_parent(self.0).map(Span)
652    }
653
654    /// The span for the origin source code that `self` was generated from. If
655    /// this `Span` wasn't generated from other macro expansions then the return
656    /// value is the same as `*self`.
657    #[unstable(feature = "proc_macro_span", issue = "54725")]
658    pub fn source(&self) -> Span {
659        Span(BridgeMethods::span_source(self.0))
660    }
661
662    /// Returns the span's byte position range in the source file.
663    #[unstable(feature = "proc_macro_span", issue = "54725")]
664    pub fn byte_range(&self) -> Range<usize> {
665        BridgeMethods::span_byte_range(self.0)
666    }
667
668    /// Creates an empty span pointing to directly before this span.
669    #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
670    pub fn start(&self) -> Span {
671        Span(BridgeMethods::span_start(self.0))
672    }
673
674    /// Creates an empty span pointing to directly after this span.
675    #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
676    pub fn end(&self) -> Span {
677        Span(BridgeMethods::span_end(self.0))
678    }
679
680    /// The one-indexed line of the source file where the span starts.
681    ///
682    /// To obtain the line of the span's end, use `span.end().line()`.
683    #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
684    pub fn line(&self) -> usize {
685        BridgeMethods::span_line(self.0)
686    }
687
688    /// The one-indexed column of the source file where the span starts.
689    ///
690    /// To obtain the column of the span's end, use `span.end().column()`.
691    #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
692    pub fn column(&self) -> usize {
693        BridgeMethods::span_column(self.0)
694    }
695
696    /// The path to the source file in which this span occurs, for display purposes.
697    ///
698    /// This might not correspond to a valid file system path.
699    /// It might be remapped (e.g. `"/src/lib.rs"`) or an artificial path (e.g. `"<command line>"`).
700    #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
701    pub fn file(&self) -> String {
702        BridgeMethods::span_file(self.0)
703    }
704
705    /// The path to the source file in which this span occurs on the local file system.
706    ///
707    /// This is the actual path on disk. It is unaffected by path remapping.
708    ///
709    /// This path should not be embedded in the output of the macro; prefer `file()` instead.
710    #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
711    pub fn local_file(&self) -> Option<PathBuf> {
712        BridgeMethods::span_local_file(self.0).map(PathBuf::from)
713    }
714
715    /// Creates a new span encompassing `self` and `other`.
716    ///
717    /// Returns `None` if `self` and `other` are from different files.
718    #[unstable(feature = "proc_macro_span", issue = "54725")]
719    pub fn join(&self, other: Span) -> Option<Span> {
720        BridgeMethods::span_join(self.0, other.0).map(Span)
721    }
722
723    /// Creates a new span with the same line/column information as `self` but
724    /// that resolves symbols as though it were at `other`.
725    #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
726    pub fn resolved_at(&self, other: Span) -> Span {
727        Span(BridgeMethods::span_resolved_at(self.0, other.0))
728    }
729
730    /// Creates a new span with the same name resolution behavior as `self` but
731    /// with the line/column information of `other`.
732    #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
733    pub fn located_at(&self, other: Span) -> Span {
734        other.resolved_at(*self)
735    }
736
737    /// Compares two spans to see if they're equal.
738    #[unstable(feature = "proc_macro_span", issue = "54725")]
739    pub fn eq(&self, other: &Span) -> bool {
740        self.0 == other.0
741    }
742
743    /// Returns the source text behind a span. This preserves the original source
744    /// code, including spaces and comments. It only returns a result if the span
745    /// corresponds to real source code.
746    ///
747    /// Note: The observable result of a macro should only rely on the tokens and
748    /// not on this source text. The result of this function is a best effort to
749    /// be used for diagnostics only.
750    #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
751    pub fn source_text(&self) -> Option<String> {
752        BridgeMethods::span_source_text(self.0)
753    }
754
755    // Used by the implementation of `Span::quote`
756    #[doc(hidden)]
757    #[unstable(feature = "proc_macro_internals", issue = "27812")]
758    pub fn save_span(&self) -> usize {
759        BridgeMethods::span_save_span(self.0)
760    }
761
762    // Used by the implementation of `Span::quote`
763    #[doc(hidden)]
764    #[unstable(feature = "proc_macro_internals", issue = "27812")]
765    pub fn recover_proc_macro_span(id: usize) -> Span {
766        Span(BridgeMethods::span_recover_proc_macro_span(id))
767    }
768
769    diagnostic_method!(error, Level::Error);
770    diagnostic_method!(warning, Level::Warning);
771    diagnostic_method!(note, Level::Note);
772    diagnostic_method!(help, Level::Help);
773}
774
775/// Prints a span in a form convenient for debugging.
776#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
777impl fmt::Debug for Span {
778    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
779        self.0.fmt(f)
780    }
781}
782
783/// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
784#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
785#[derive(Clone)]
786pub enum TokenTree {
787    /// A token stream surrounded by bracket delimiters.
788    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789    Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
790    /// An identifier.
791    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
792    Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
793    /// A single punctuation character (`+`, `,`, `$`, etc.).
794    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
795    Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
796    /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
797    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
798    Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
799}
800
801#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
802impl !Send for TokenTree {}
803#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
804impl !Sync for TokenTree {}
805
806impl TokenTree {
807    /// Returns the span of this tree, delegating to the `span` method of
808    /// the contained token or a delimited stream.
809    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
810    pub fn span(&self) -> Span {
811        match *self {
812            TokenTree::Group(ref t) => t.span(),
813            TokenTree::Ident(ref t) => t.span(),
814            TokenTree::Punct(ref t) => t.span(),
815            TokenTree::Literal(ref t) => t.span(),
816        }
817    }
818
819    /// Configures the span for *only this token*.
820    ///
821    /// Note that if this token is a `Group` then this method will not configure
822    /// the span of each of the internal tokens, this will simply delegate to
823    /// the `set_span` method of each variant.
824    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
825    pub fn set_span(&mut self, span: Span) {
826        match *self {
827            TokenTree::Group(ref mut t) => t.set_span(span),
828            TokenTree::Ident(ref mut t) => t.set_span(span),
829            TokenTree::Punct(ref mut t) => t.set_span(span),
830            TokenTree::Literal(ref mut t) => t.set_span(span),
831        }
832    }
833}
834
835/// Prints token tree in a form convenient for debugging.
836#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
837impl fmt::Debug for TokenTree {
838    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839        // Each of these has the name in the struct type in the derived debug,
840        // so don't bother with an extra layer of indirection
841        match *self {
842            TokenTree::Group(ref tt) => tt.fmt(f),
843            TokenTree::Ident(ref tt) => tt.fmt(f),
844            TokenTree::Punct(ref tt) => tt.fmt(f),
845            TokenTree::Literal(ref tt) => tt.fmt(f),
846        }
847    }
848}
849
850#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
851impl From<Group> for TokenTree {
852    fn from(g: Group) -> TokenTree {
853        TokenTree::Group(g)
854    }
855}
856
857#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
858impl From<Ident> for TokenTree {
859    fn from(g: Ident) -> TokenTree {
860        TokenTree::Ident(g)
861    }
862}
863
864#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
865impl From<Punct> for TokenTree {
866    fn from(g: Punct) -> TokenTree {
867        TokenTree::Punct(g)
868    }
869}
870
871#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
872impl From<Literal> for TokenTree {
873    fn from(g: Literal) -> TokenTree {
874        TokenTree::Literal(g)
875    }
876}
877
878/// Prints the token tree as a string that is supposed to be losslessly convertible back
879/// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
880/// with `Delimiter::None` delimiters and negative numeric literals.
881///
882/// Note: the exact form of the output is subject to change, e.g. there might
883/// be changes in the whitespace used between tokens. Therefore, you should
884/// *not* do any kind of simple substring matching on the output string (as
885/// produced by `to_string`) to implement a proc macro, because that matching
886/// might stop working if such changes happen. Instead, you should work at the
887/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
888/// `TokenTree::Punct`, or `TokenTree::Literal`.
889#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
890impl fmt::Display for TokenTree {
891    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892        match self {
893            TokenTree::Group(t) => write!(f, "{t}"),
894            TokenTree::Ident(t) => write!(f, "{t}"),
895            TokenTree::Punct(t) => write!(f, "{t}"),
896            TokenTree::Literal(t) => write!(f, "{t}"),
897        }
898    }
899}
900
901/// A delimited token stream.
902///
903/// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
904#[derive(Clone)]
905#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
906pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
907
908#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
909impl !Send for Group {}
910#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
911impl !Sync for Group {}
912
913/// Describes how a sequence of token trees is delimited.
914#[derive(Copy, Clone, Debug, PartialEq, Eq)]
915#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
916pub enum Delimiter {
917    /// `( ... )`
918    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
919    Parenthesis,
920    /// `{ ... }`
921    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
922    Brace,
923    /// `[ ... ]`
924    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
925    Bracket,
926    /// `∅ ... ∅`
927    /// An invisible delimiter, that may, for example, appear around tokens coming from a
928    /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
929    /// `$var * 3` where `$var` is `1 + 2`.
930    /// Invisible delimiters might not survive roundtrip of a token stream through a string.
931    ///
932    /// <div class="warning">
933    ///
934    /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
935    /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
936    /// of a proc_macro macro are preserved, and only in very specific circumstances.
937    /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
938    /// operator priorities as indicated above. The other `Delimiter` variants should be used
939    /// instead in this context. This is a rustc bug. For details, see
940    /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
941    ///
942    /// </div>
943    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
944    None,
945}
946
947impl Group {
948    /// Creates a new `Group` with the given delimiter and token stream.
949    ///
950    /// This constructor will set the span for this group to
951    /// `Span::call_site()`. To change the span you can use the `set_span`
952    /// method below.
953    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
954    pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
955        Group(bridge::Group {
956            delimiter,
957            stream: stream.0,
958            span: bridge::DelimSpan::from_single(Span::call_site().0),
959        })
960    }
961
962    /// Returns the delimiter of this `Group`
963    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
964    pub fn delimiter(&self) -> Delimiter {
965        self.0.delimiter
966    }
967
968    /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
969    ///
970    /// Note that the returned token stream does not include the delimiter
971    /// returned above.
972    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
973    pub fn stream(&self) -> TokenStream {
974        TokenStream(self.0.stream.clone())
975    }
976
977    /// Returns the span for the delimiters of this token stream, spanning the
978    /// entire `Group`.
979    ///
980    /// ```text
981    /// pub fn span(&self) -> Span {
982    ///            ^^^^^^^
983    /// ```
984    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
985    pub fn span(&self) -> Span {
986        Span(self.0.span.entire)
987    }
988
989    /// Returns the span pointing to the opening delimiter of this group.
990    ///
991    /// ```text
992    /// pub fn span_open(&self) -> Span {
993    ///                 ^
994    /// ```
995    #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
996    pub fn span_open(&self) -> Span {
997        Span(self.0.span.open)
998    }
999
1000    /// Returns the span pointing to the closing delimiter of this group.
1001    ///
1002    /// ```text
1003    /// pub fn span_close(&self) -> Span {
1004    ///                        ^
1005    /// ```
1006    #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
1007    pub fn span_close(&self) -> Span {
1008        Span(self.0.span.close)
1009    }
1010
1011    /// Configures the span for this `Group`'s delimiters, but not its internal
1012    /// tokens.
1013    ///
1014    /// This method will **not** set the span of all the internal tokens spanned
1015    /// by this group, but rather it will only set the span of the delimiter
1016    /// tokens at the level of the `Group`.
1017    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1018    pub fn set_span(&mut self, span: Span) {
1019        self.0.span = bridge::DelimSpan::from_single(span.0);
1020    }
1021}
1022
1023/// Prints the group as a string that should be losslessly convertible back
1024/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
1025/// with `Delimiter::None` delimiters.
1026#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1027impl fmt::Display for Group {
1028    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1029        write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
1030    }
1031}
1032
1033#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1034impl fmt::Debug for Group {
1035    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036        f.debug_struct("Group")
1037            .field("delimiter", &self.delimiter())
1038            .field("stream", &self.stream())
1039            .field("span", &self.span())
1040            .finish()
1041    }
1042}
1043
1044/// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
1045///
1046/// Multi-character operators like `+=` are represented as two instances of `Punct` with different
1047/// forms of `Spacing` returned.
1048#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1049#[derive(Clone)]
1050pub struct Punct(bridge::Punct<bridge::client::Span>);
1051
1052#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1053impl !Send for Punct {}
1054#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1055impl !Sync for Punct {}
1056
1057/// Indicates whether a `Punct` token can join with the following token
1058/// to form a multi-character operator.
1059#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1060#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1061pub enum Spacing {
1062    /// A `Punct` token can join with the following token to form a multi-character operator.
1063    ///
1064    /// In token streams constructed using proc macro interfaces, `Joint` punctuation tokens can be
1065    /// followed by any other tokens. However, in token streams parsed from source code, the
1066    /// compiler will only set spacing to `Joint` in the following cases.
1067    /// - When a `Punct` is immediately followed by another `Punct` without a whitespace. E.g. `+`
1068    ///   is `Joint` in `+=` and `++`.
1069    /// - When a single quote `'` is immediately followed by an identifier without a whitespace.
1070    ///   E.g. `'` is `Joint` in `'lifetime`.
1071    ///
1072    /// This list may be extended in the future to enable more token combinations.
1073    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1074    Joint,
1075    /// A `Punct` token cannot join with the following token to form a multi-character operator.
1076    ///
1077    /// `Alone` punctuation tokens can be followed by any other tokens. In token streams parsed
1078    /// from source code, the compiler will set spacing to `Alone` in all cases not covered by the
1079    /// conditions for `Joint` above. E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`. In
1080    /// particular, tokens not followed by anything will be marked as `Alone`.
1081    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1082    Alone,
1083}
1084
1085impl Punct {
1086    /// Creates a new `Punct` from the given character and spacing.
1087    /// The `ch` argument must be a valid punctuation character permitted by the language,
1088    /// otherwise the function will panic.
1089    ///
1090    /// The returned `Punct` will have the default span of `Span::call_site()`
1091    /// which can be further configured with the `set_span` method below.
1092    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1093    pub fn new(ch: char, spacing: Spacing) -> Punct {
1094        const LEGAL_CHARS: &[char] = &[
1095            '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
1096            ':', '#', '$', '?', '\'',
1097        ];
1098        if !LEGAL_CHARS.contains(&ch) {
1099            panic!("unsupported character `{:?}`", ch);
1100        }
1101        Punct(bridge::Punct {
1102            ch: ch as u8,
1103            joint: spacing == Spacing::Joint,
1104            span: Span::call_site().0,
1105        })
1106    }
1107
1108    /// Returns the value of this punctuation character as `char`.
1109    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1110    pub fn as_char(&self) -> char {
1111        self.0.ch as char
1112    }
1113
1114    /// Returns the spacing of this punctuation character, indicating whether it can be potentially
1115    /// combined into a multi-character operator with the following token (`Joint`), or whether the
1116    /// operator has definitely ended (`Alone`).
1117    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1118    pub fn spacing(&self) -> Spacing {
1119        if self.0.joint { Spacing::Joint } else { Spacing::Alone }
1120    }
1121
1122    /// Returns the span for this punctuation character.
1123    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1124    pub fn span(&self) -> Span {
1125        Span(self.0.span)
1126    }
1127
1128    /// Configure the span for this punctuation character.
1129    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1130    pub fn set_span(&mut self, span: Span) {
1131        self.0.span = span.0;
1132    }
1133}
1134
1135/// Prints the punctuation character as a string that should be losslessly convertible
1136/// back into the same character.
1137#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1138impl fmt::Display for Punct {
1139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1140        write!(f, "{}", self.as_char())
1141    }
1142}
1143
1144#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1145impl fmt::Debug for Punct {
1146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1147        f.debug_struct("Punct")
1148            .field("ch", &self.as_char())
1149            .field("spacing", &self.spacing())
1150            .field("span", &self.span())
1151            .finish()
1152    }
1153}
1154
1155#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1156impl PartialEq<char> for Punct {
1157    fn eq(&self, rhs: &char) -> bool {
1158        self.as_char() == *rhs
1159    }
1160}
1161
1162#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1163impl PartialEq<Punct> for char {
1164    fn eq(&self, rhs: &Punct) -> bool {
1165        *self == rhs.as_char()
1166    }
1167}
1168
1169/// An identifier (`ident`).
1170#[derive(Clone)]
1171#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1172pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1173
1174impl Ident {
1175    /// Creates a new `Ident` with the given `string` as well as the specified
1176    /// `span`.
1177    /// The `string` argument must be a valid identifier permitted by the
1178    /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1179    ///
1180    /// The constructed identifier will be NFC-normalized. See the [Reference] for more info.
1181    ///
1182    /// Note that `span`, currently in rustc, configures the hygiene information
1183    /// for this identifier.
1184    ///
1185    /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1186    /// meaning that identifiers created with this span will be resolved as if they were written
1187    /// directly at the location of the macro call, and other code at the macro call site will be
1188    /// able to refer to them as well.
1189    ///
1190    /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1191    /// meaning that identifiers created with this span will be resolved at the location of the
1192    /// macro definition and other code at the macro call site will not be able to refer to them.
1193    ///
1194    /// Due to the current importance of hygiene this constructor, unlike other
1195    /// tokens, requires a `Span` to be specified at construction.
1196    ///
1197    /// [Reference]: https://doc.rust-lang.org/nightly/reference/identifiers.html#r-ident.normalization
1198    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1199    pub fn new(string: &str, span: Span) -> Ident {
1200        Ident(bridge::Ident {
1201            sym: bridge::client::Symbol::new_ident(string, false),
1202            is_raw: false,
1203            span: span.0,
1204        })
1205    }
1206
1207    /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1208    /// The `string` argument be a valid identifier permitted by the language
1209    /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1210    /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1211    #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1212    pub fn new_raw(string: &str, span: Span) -> Ident {
1213        Ident(bridge::Ident {
1214            sym: bridge::client::Symbol::new_ident(string, true),
1215            is_raw: true,
1216            span: span.0,
1217        })
1218    }
1219
1220    /// Returns the span of this `Ident`, encompassing the entire string returned
1221    /// by [`to_string`](ToString::to_string).
1222    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1223    pub fn span(&self) -> Span {
1224        Span(self.0.span)
1225    }
1226
1227    /// Configures the span of this `Ident`, possibly changing its hygiene context.
1228    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1229    pub fn set_span(&mut self, span: Span) {
1230        self.0.span = span.0;
1231    }
1232}
1233
1234/// Prints the identifier as a string that should be losslessly convertible back
1235/// into the same identifier.
1236#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1237impl fmt::Display for Ident {
1238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1239        if self.0.is_raw {
1240            f.write_str("r#")?;
1241        }
1242        fmt::Display::fmt(&self.0.sym, f)
1243    }
1244}
1245
1246#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1247impl fmt::Debug for Ident {
1248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1249        f.debug_struct("Ident")
1250            .field("ident", &self.to_string())
1251            .field("span", &self.span())
1252            .finish()
1253    }
1254}
1255
1256/// A literal string (`"hello"`), byte string (`b"hello"`), C string (`c"hello"`),
1257/// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1258/// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1259/// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1260#[derive(Clone)]
1261#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1262pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1263
1264macro_rules! suffixed_int_literals {
1265    ($($name:ident => $kind:ident,)*) => ($(
1266        /// Creates a new suffixed integer literal with the specified value.
1267        ///
1268        /// This function will create an integer like `1u32` where the integer
1269        /// value specified is the first part of the token and the integral is
1270        /// also suffixed at the end.
1271        /// Literals created from negative numbers might not survive round-trips through
1272        /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1273        ///
1274        /// Literals created through this method have the `Span::call_site()`
1275        /// span by default, which can be configured with the `set_span` method
1276        /// below.
1277        #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1278        pub fn $name(n: $kind) -> Literal {
1279            Literal(bridge::Literal {
1280                kind: bridge::LitKind::Integer,
1281                symbol: bridge::client::Symbol::new(&n.to_string()),
1282                suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1283                span: Span::call_site().0,
1284            })
1285        }
1286    )*)
1287}
1288
1289macro_rules! unsuffixed_int_literals {
1290    ($($name:ident => $kind:ident,)*) => ($(
1291        /// Creates a new unsuffixed integer literal with the specified value.
1292        ///
1293        /// This function will create an integer like `1` where the integer
1294        /// value specified is the first part of the token. No suffix is
1295        /// specified on this token, meaning that invocations like
1296        /// `Literal::i8_unsuffixed(1)` are equivalent to
1297        /// `Literal::u32_unsuffixed(1)`.
1298        /// Literals created from negative numbers might not survive rountrips through
1299        /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1300        ///
1301        /// Literals created through this method have the `Span::call_site()`
1302        /// span by default, which can be configured with the `set_span` method
1303        /// below.
1304        #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1305        pub fn $name(n: $kind) -> Literal {
1306            Literal(bridge::Literal {
1307                kind: bridge::LitKind::Integer,
1308                symbol: bridge::client::Symbol::new(&n.to_string()),
1309                suffix: None,
1310                span: Span::call_site().0,
1311            })
1312        }
1313    )*)
1314}
1315
1316macro_rules! integer_values {
1317    ($($nb:ident => $fn_name:ident,)+) => {
1318        $(
1319            #[doc = concat!(
1320                "Returns the unescaped `",
1321                stringify!($nb),
1322                "` value if the literal is a `",
1323                stringify!($nb),
1324                "` or if it's an \"unmarked\" integer which doesn't overflow.")]
1325            #[unstable(feature = "proc_macro_value", issue = "136652")]
1326            pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1327                if self.0.kind != bridge::LitKind::Integer {
1328                    return Err(ConversionErrorKind::InvalidLiteralKind);
1329                }
1330                self.with_symbol_and_suffix(|symbol, suffix| {
1331                    match suffix {
1332                        stringify!($nb) | "" => {
1333                            let symbol = strip_underscores(symbol);
1334                            let (number, base) = parse_number(&symbol);
1335                            $nb::from_str_radix(&number, base as u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1336                        }
1337                        _ => Err(ConversionErrorKind::InvalidLiteralKind),
1338                    }
1339                })
1340            }
1341        )+
1342    }
1343}
1344
1345macro_rules! float_values {
1346    ($($nb:ident => $fn_name:ident,)+) => {
1347        $(
1348            #[doc = concat!(
1349                "Returns the unescaped `",
1350                stringify!($nb),
1351                "` value if the literal is a `",
1352                stringify!($nb),
1353                "` or if it's an \"unmarked\" float which doesn't overflow.")]
1354            #[unstable(feature = "proc_macro_value", issue = "136652")]
1355            pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1356                if self.0.kind != bridge::LitKind::Float {
1357                    return Err(ConversionErrorKind::InvalidLiteralKind);
1358                }
1359                self.with_symbol_and_suffix(|symbol, suffix| {
1360                    match suffix {
1361                        stringify!($nb) | "" => {
1362                            let number = strip_underscores(symbol);
1363                            $nb::from_str(&number).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1364                        }
1365                        _ => Err(ConversionErrorKind::InvalidLiteralKind),
1366                    }
1367                })
1368            }
1369        )+
1370    }
1371}
1372
1373impl Literal {
1374    fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1375        Literal(bridge::Literal {
1376            kind,
1377            symbol: bridge::client::Symbol::new(value),
1378            suffix: suffix.map(bridge::client::Symbol::new),
1379            span: Span::call_site().0,
1380        })
1381    }
1382
1383    suffixed_int_literals! {
1384        u8_suffixed => u8,
1385        u16_suffixed => u16,
1386        u32_suffixed => u32,
1387        u64_suffixed => u64,
1388        u128_suffixed => u128,
1389        usize_suffixed => usize,
1390        i8_suffixed => i8,
1391        i16_suffixed => i16,
1392        i32_suffixed => i32,
1393        i64_suffixed => i64,
1394        i128_suffixed => i128,
1395        isize_suffixed => isize,
1396    }
1397
1398    unsuffixed_int_literals! {
1399        u8_unsuffixed => u8,
1400        u16_unsuffixed => u16,
1401        u32_unsuffixed => u32,
1402        u64_unsuffixed => u64,
1403        u128_unsuffixed => u128,
1404        usize_unsuffixed => usize,
1405        i8_unsuffixed => i8,
1406        i16_unsuffixed => i16,
1407        i32_unsuffixed => i32,
1408        i64_unsuffixed => i64,
1409        i128_unsuffixed => i128,
1410        isize_unsuffixed => isize,
1411    }
1412
1413    /// Creates a new unsuffixed floating-point literal.
1414    ///
1415    /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1416    /// the float's value is emitted directly into the token but no suffix is
1417    /// used, so it may be inferred to be a `f64` later in the compiler.
1418    /// Literals created from negative numbers might not survive rountrips through
1419    /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1420    ///
1421    /// # Panics
1422    ///
1423    /// This function requires that the specified float is finite, for
1424    /// example if it is infinity or NaN this function will panic.
1425    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1426    pub fn f32_unsuffixed(n: f32) -> Literal {
1427        if !n.is_finite() {
1428            panic!("Invalid float literal {n}");
1429        }
1430        let mut repr = n.to_string();
1431        if !repr.contains('.') {
1432            repr.push_str(".0");
1433        }
1434        Literal::new(bridge::LitKind::Float, &repr, None)
1435    }
1436
1437    /// Creates a new suffixed floating-point literal.
1438    ///
1439    /// This constructor will create a literal like `1.0f32` where the value
1440    /// specified is the preceding part of the token and `f32` is the suffix of
1441    /// the token. This token will always be inferred to be an `f32` in the
1442    /// compiler.
1443    /// Literals created from negative numbers might not survive rountrips through
1444    /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1445    ///
1446    /// # Panics
1447    ///
1448    /// This function requires that the specified float is finite, for
1449    /// example if it is infinity or NaN this function will panic.
1450    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1451    pub fn f32_suffixed(n: f32) -> Literal {
1452        if !n.is_finite() {
1453            panic!("Invalid float literal {n}");
1454        }
1455        Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1456    }
1457
1458    /// Creates a new unsuffixed floating-point literal.
1459    ///
1460    /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1461    /// the float's value is emitted directly into the token but no suffix is
1462    /// used, so it may be inferred to be a `f64` later in the compiler.
1463    /// Literals created from negative numbers might not survive rountrips through
1464    /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1465    ///
1466    /// # Panics
1467    ///
1468    /// This function requires that the specified float is finite, for
1469    /// example if it is infinity or NaN this function will panic.
1470    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1471    pub fn f64_unsuffixed(n: f64) -> Literal {
1472        if !n.is_finite() {
1473            panic!("Invalid float literal {n}");
1474        }
1475        let mut repr = n.to_string();
1476        if !repr.contains('.') {
1477            repr.push_str(".0");
1478        }
1479        Literal::new(bridge::LitKind::Float, &repr, None)
1480    }
1481
1482    /// Creates a new suffixed floating-point literal.
1483    ///
1484    /// This constructor will create a literal like `1.0f64` where the value
1485    /// specified is the preceding part of the token and `f64` is the suffix of
1486    /// the token. This token will always be inferred to be an `f64` in the
1487    /// compiler.
1488    /// Literals created from negative numbers might not survive rountrips through
1489    /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1490    ///
1491    /// # Panics
1492    ///
1493    /// This function requires that the specified float is finite, for
1494    /// example if it is infinity or NaN this function will panic.
1495    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1496    pub fn f64_suffixed(n: f64) -> Literal {
1497        if !n.is_finite() {
1498            panic!("Invalid float literal {n}");
1499        }
1500        Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1501    }
1502
1503    /// String literal.
1504    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1505    pub fn string(string: &str) -> Literal {
1506        let escape = EscapeOptions {
1507            escape_single_quote: false,
1508            escape_double_quote: true,
1509            escape_nonascii: false,
1510        };
1511        let repr = escape_bytes(string.as_bytes(), escape);
1512        Literal::new(bridge::LitKind::Str, &repr, None)
1513    }
1514
1515    /// Character literal.
1516    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1517    pub fn character(ch: char) -> Literal {
1518        let escape = EscapeOptions {
1519            escape_single_quote: true,
1520            escape_double_quote: false,
1521            escape_nonascii: false,
1522        };
1523        let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1524        Literal::new(bridge::LitKind::Char, &repr, None)
1525    }
1526
1527    /// Byte character literal.
1528    #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1529    pub fn byte_character(byte: u8) -> Literal {
1530        let escape = EscapeOptions {
1531            escape_single_quote: true,
1532            escape_double_quote: false,
1533            escape_nonascii: true,
1534        };
1535        let repr = escape_bytes(&[byte], escape);
1536        Literal::new(bridge::LitKind::Byte, &repr, None)
1537    }
1538
1539    /// Byte string literal.
1540    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1541    pub fn byte_string(bytes: &[u8]) -> Literal {
1542        let escape = EscapeOptions {
1543            escape_single_quote: false,
1544            escape_double_quote: true,
1545            escape_nonascii: true,
1546        };
1547        let repr = escape_bytes(bytes, escape);
1548        Literal::new(bridge::LitKind::ByteStr, &repr, None)
1549    }
1550
1551    /// C string literal.
1552    #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1553    pub fn c_string(string: &CStr) -> Literal {
1554        let escape = EscapeOptions {
1555            escape_single_quote: false,
1556            escape_double_quote: true,
1557            escape_nonascii: false,
1558        };
1559        let repr = escape_bytes(string.to_bytes(), escape);
1560        Literal::new(bridge::LitKind::CStr, &repr, None)
1561    }
1562
1563    /// Returns the span encompassing this literal.
1564    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1565    pub fn span(&self) -> Span {
1566        Span(self.0.span)
1567    }
1568
1569    /// Configures the span associated for this literal.
1570    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1571    pub fn set_span(&mut self, span: Span) {
1572        self.0.span = span.0;
1573    }
1574
1575    /// Returns a `Span` that is a subset of `self.span()` containing only the
1576    /// source bytes in range `range`. Returns `None` if the would-be trimmed
1577    /// span is outside the bounds of `self`.
1578    // FIXME(SergioBenitez): check that the byte range starts and ends at a
1579    // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1580    // occur elsewhere when the source text is printed.
1581    // FIXME(SergioBenitez): there is no way for the user to know what
1582    // `self.span()` actually maps to, so this method can currently only be
1583    // called blindly. For example, `to_string()` for the character 'c' returns
1584    // "'\u{63}'"; there is no way for the user to know whether the source text
1585    // was 'c' or whether it was '\u{63}'.
1586    #[unstable(feature = "proc_macro_span", issue = "54725")]
1587    pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1588        BridgeMethods::span_subspan(
1589            self.0.span,
1590            range.start_bound().cloned(),
1591            range.end_bound().cloned(),
1592        )
1593        .map(Span)
1594    }
1595
1596    fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1597        self.0.symbol.with(|symbol| match self.0.suffix {
1598            Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1599            None => f(symbol, ""),
1600        })
1601    }
1602
1603    /// Invokes the callback with a `&[&str]` consisting of each part of the
1604    /// literal's representation. This is done to allow the `ToString` and
1605    /// `Display` implementations to borrow references to symbol values, and
1606    /// both be optimized to reduce overhead.
1607    fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1608        /// Returns a string containing exactly `num` '#' characters.
1609        /// Uses a 256-character source string literal which is always safe to
1610        /// index with a `u8` index.
1611        fn get_hashes_str(num: u8) -> &'static str {
1612            const HASHES: &str = "\
1613            ################################################################\
1614            ################################################################\
1615            ################################################################\
1616            ################################################################\
1617            ";
1618            const _: () = assert!(HASHES.len() == 256);
1619            &HASHES[..num as usize]
1620        }
1621
1622        self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1623            bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1624            bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1625            bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1626            bridge::LitKind::StrRaw(n) => {
1627                let hashes = get_hashes_str(n);
1628                f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1629            }
1630            bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1631            bridge::LitKind::ByteStrRaw(n) => {
1632                let hashes = get_hashes_str(n);
1633                f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1634            }
1635            bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1636            bridge::LitKind::CStrRaw(n) => {
1637                let hashes = get_hashes_str(n);
1638                f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1639            }
1640
1641            bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1642                f(&[symbol, suffix])
1643            }
1644        })
1645    }
1646
1647    /// Returns the unescaped character value if the current literal is a byte character literal.
1648    #[unstable(feature = "proc_macro_value", issue = "136652")]
1649    pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1650        self.0.symbol.with(|symbol| match self.0.kind {
1651            bridge::LitKind::Byte => unescape_byte(symbol)
1652                .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1653            _ => Err(ConversionErrorKind::InvalidLiteralKind),
1654        })
1655    }
1656
1657    /// Returns the unescaped character value if the current literal is a character literal.
1658    #[unstable(feature = "proc_macro_value", issue = "136652")]
1659    pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1660        self.0.symbol.with(|symbol| match self.0.kind {
1661            bridge::LitKind::Char => unescape_char(symbol)
1662                .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1663            _ => Err(ConversionErrorKind::InvalidLiteralKind),
1664        })
1665    }
1666
1667    /// Returns the unescaped string value if the current literal is a string or a string literal.
1668    #[unstable(feature = "proc_macro_value", issue = "136652")]
1669    pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1670        self.0.symbol.with(|symbol| match self.0.kind {
1671            bridge::LitKind::Str => {
1672                if symbol.contains('\\') {
1673                    let mut buf = String::with_capacity(symbol.len());
1674                    let mut error = None;
1675                    // Force-inlining here is aggressive but the closure is
1676                    // called on every char in the string, so it can be hot in
1677                    // programs with many long strings containing escapes.
1678                    unescape_str(
1679                        symbol,
1680                        #[inline(always)]
1681                        |_, c| match c {
1682                            Ok(c) => buf.push(c),
1683                            Err(err) => {
1684                                if err.is_fatal() {
1685                                    error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1686                                }
1687                            }
1688                        },
1689                    );
1690                    if let Some(error) = error { Err(error) } else { Ok(buf) }
1691                } else {
1692                    Ok(symbol.to_string())
1693                }
1694            }
1695            bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1696            _ => Err(ConversionErrorKind::InvalidLiteralKind),
1697        })
1698    }
1699
1700    /// Returns the unescaped string value if the current literal is a c-string or a c-string
1701    /// literal.
1702    #[unstable(feature = "proc_macro_value", issue = "136652")]
1703    pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1704        self.0.symbol.with(|symbol| match self.0.kind {
1705            bridge::LitKind::CStr => {
1706                let mut error = None;
1707                let mut buf = Vec::with_capacity(symbol.len());
1708
1709                unescape_c_str(symbol, |_span, res| match res {
1710                    Ok(MixedUnit::Char(c)) => {
1711                        buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1712                    }
1713                    Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1714                    Err(err) => {
1715                        if err.is_fatal() {
1716                            error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1717                        }
1718                    }
1719                });
1720                if let Some(error) = error {
1721                    Err(error)
1722                } else {
1723                    buf.push(0);
1724                    Ok(buf)
1725                }
1726            }
1727            bridge::LitKind::CStrRaw(_) => {
1728                // Raw strings have no escapes so we can convert the symbol
1729                // directly to a `Lrc<u8>` after appending the terminating NUL
1730                // char.
1731                let mut buf = symbol.to_owned().into_bytes();
1732                buf.push(0);
1733                Ok(buf)
1734            }
1735            _ => Err(ConversionErrorKind::InvalidLiteralKind),
1736        })
1737    }
1738
1739    /// Returns the unescaped string value if the current literal is a byte string or a byte string
1740    /// literal.
1741    #[unstable(feature = "proc_macro_value", issue = "136652")]
1742    pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1743        self.0.symbol.with(|symbol| match self.0.kind {
1744            bridge::LitKind::ByteStr => {
1745                let mut buf = Vec::with_capacity(symbol.len());
1746                let mut error = None;
1747
1748                unescape_byte_str(symbol, |_, res| match res {
1749                    Ok(b) => buf.push(b),
1750                    Err(err) => {
1751                        if err.is_fatal() {
1752                            error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1753                        }
1754                    }
1755                });
1756                if let Some(error) = error { Err(error) } else { Ok(buf) }
1757            }
1758            bridge::LitKind::ByteStrRaw(_) => {
1759                // Raw strings have no escapes so we can convert the symbol
1760                // directly to a `Lrc<u8>`.
1761                Ok(symbol.to_owned().into_bytes())
1762            }
1763            _ => Err(ConversionErrorKind::InvalidLiteralKind),
1764        })
1765    }
1766
1767    integer_values! {
1768        u8 => u8_value,
1769        u16 => u16_value,
1770        u32 => u32_value,
1771        u64 => u64_value,
1772        u128 => u128_value,
1773        i8 => i8_value,
1774        i16 => i16_value,
1775        i32 => i32_value,
1776        i64 => i64_value,
1777        i128 => i128_value,
1778    }
1779
1780    float_values! {
1781        f16 => f16_value,
1782        f32 => f32_value,
1783        f64 => f64_value,
1784        // FIXME: `f128` doesn't implement `FromStr` for the moment so we cannot obtain it from
1785        // a `&str`. To be uncommented when it's added.
1786        // f128 => f128_value,
1787    }
1788}
1789
1790#[repr(u32)]
1791#[derive(PartialEq, Eq)]
1792enum Base {
1793    Decimal = 10,
1794    Binary = 2,
1795    Octal = 8,
1796    Hexadecimal = 16,
1797}
1798
1799fn parse_number(value: &str) -> (&str, Base) {
1800    let mut iter = value.as_bytes().iter().copied();
1801    let Some(first_digit) = iter.next() else {
1802        return ("0", Base::Decimal);
1803    };
1804    let Some(second_digit) = iter.next() else {
1805        return (value, Base::Decimal);
1806    };
1807
1808    let mut base = Base::Decimal;
1809    if first_digit == b'0' {
1810        // Attempt to parse encoding base.
1811        match second_digit {
1812            b'b' => {
1813                base = Base::Binary;
1814            }
1815            b'o' => {
1816                base = Base::Octal;
1817            }
1818            b'x' => {
1819                base = Base::Hexadecimal;
1820            }
1821            _ => {}
1822        }
1823    }
1824
1825    let offset = if base == Base::Decimal { 0 } else { 2 };
1826
1827    (&value[offset..], base)
1828}
1829
1830fn strip_underscores(value_s: &str) -> Cow<'_, str> {
1831    let value = value_s.as_bytes();
1832    if value.iter().copied().all(|c| c != b'_' && c != b'f') {
1833        return Cow::Borrowed(value_s);
1834    }
1835    let mut output = String::with_capacity(value.len());
1836    for c in value.iter().copied() {
1837        if c != b'_' {
1838            output.push(c as char);
1839        }
1840    }
1841    Cow::Owned(output)
1842}
1843
1844/// Parse a single literal from its stringified representation.
1845///
1846/// In order to parse successfully, the input string must not contain anything
1847/// but the literal token. Specifically, it must not contain whitespace or
1848/// comments in addition to the literal.
1849///
1850/// The resulting literal token will have a `Span::call_site()` span.
1851///
1852/// NOTE: some errors may cause panics instead of returning `LexError`. We
1853/// reserve the right to change these errors into `LexError`s later.
1854#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1855impl FromStr for Literal {
1856    type Err = LexError;
1857
1858    fn from_str(src: &str) -> Result<Self, LexError> {
1859        match BridgeMethods::literal_from_str(src) {
1860            Ok(literal) => Ok(Literal(literal)),
1861            Err(msg) => Err(LexError(msg)),
1862        }
1863    }
1864}
1865
1866/// Prints the literal as a string that should be losslessly convertible
1867/// back into the same literal (except for possible rounding for floating point literals).
1868#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1869impl fmt::Display for Literal {
1870    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1871        self.with_stringify_parts(|parts| {
1872            for part in parts {
1873                fmt::Display::fmt(part, f)?;
1874            }
1875            Ok(())
1876        })
1877    }
1878}
1879
1880#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1881impl fmt::Debug for Literal {
1882    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1883        f.debug_struct("Literal")
1884            // format the kind on one line even in {:#?} mode
1885            .field("kind", &format_args!("{:?}", self.0.kind))
1886            .field("symbol", &self.0.symbol)
1887            // format `Some("...")` on one line even in {:#?} mode
1888            .field("suffix", &format_args!("{:?}", self.0.suffix))
1889            .field("span", &self.0.span)
1890            .finish()
1891    }
1892}
1893
1894#[unstable(
1895    feature = "proc_macro_tracked_path",
1896    issue = "99515",
1897    implied_by = "proc_macro_tracked_env"
1898)]
1899/// Functionality for adding environment state to the build dependency info.
1900pub mod tracked {
1901    use std::env::{self, VarError};
1902    use std::ffi::OsStr;
1903    use std::path::Path;
1904
1905    use crate::BridgeMethods;
1906
1907    /// Retrieve an environment variable and add it to build dependency info.
1908    /// The build system executing the compiler will know that the variable was accessed during
1909    /// compilation, and will be able to rerun the build when the value of that variable changes.
1910    /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1911    /// standard library, except that the argument must be UTF-8.
1912    #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1913    pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1914        let key: &str = key.as_ref();
1915        let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1916        BridgeMethods::track_env_var(key, value.as_deref().ok());
1917        value
1918    }
1919
1920    /// Track a file or directory explicitly.
1921    ///
1922    /// Commonly used for tracking asset preprocessing.
1923    #[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1924    pub fn path<P: AsRef<Path>>(path: P) {
1925        let path: &str = path.as_ref().to_str().unwrap();
1926        BridgeMethods::track_path(path);
1927    }
1928}