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