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