proc_macro/
lib.rs

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