Skip to main content

proc_macro/
lib.rs

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