Skip to main content

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