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