Skip to main content

proc_macro/
lib.rs

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