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
1112#![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)]
3839#[unstable(feature = "proc_macro_internals", issue = "27812")]
40#[doc(hidden)]
41pub mod bridge;
4243mod diagnostic;
44mod escape;
45mod to_tokens;
4647use core::ops::BitOr;
48use std::ffi::CStr;
49use std::ops::{Range, RangeBounds};
50use std::path::PathBuf;
51use std::str::FromStr;
52use std::{error, fmt};
5354#[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::{
59MixedUnit, 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;
6364use crate::bridge::client::Methodsas BridgeMethods;
65use crate::escape::{EscapeOptions, escape_bytes};
6667/// Errors returned when trying to retrieve a literal unescaped value.
68#[unstable(feature = "proc_macro_value", issue = "136652")]
69#[derive(#[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::fmt::Debug for ConversionErrorKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ConversionErrorKind::FailedToUnescape(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FailedToUnescape", &__self_0),
ConversionErrorKind::InvalidLiteralKind =>
::core::fmt::Formatter::write_str(f, "InvalidLiteralKind"),
}
}
}Debug, #[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::PartialEq for ConversionErrorKind {
#[inline]
fn eq(&self, other: &ConversionErrorKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ConversionErrorKind::FailedToUnescape(__self_0),
ConversionErrorKind::FailedToUnescape(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::Eq for ConversionErrorKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<EscapeError>;
}
}Eq)]
70pub enum ConversionErrorKind {
71/// The literal failed to be escaped, take a look at [`EscapeError`] for more information.
72FailedToUnescape(EscapeError),
73/// Trying to convert a literal with the wrong type.
74InvalidLiteralKind,
75}
7677/// 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}
9495/// 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(#[automatically_derived]
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ::core::clone::Clone for TokenStream {
#[inline]
fn clone(&self) -> TokenStream {
TokenStream(::core::clone::Clone::clone(&self.0))
}
}Clone)]
105pub struct TokenStream(Option<bridge::client::TokenStream>);
106107#[stable(feature = "proc_macro_lib", since = "1.15.0")]
108impl !Sendfor TokenStream {}
109#[stable(feature = "proc_macro_lib", since = "1.15.0")]
110impl !Syncfor TokenStream {}
111112/// Error returned from `TokenStream::from_str`.
113#[stable(feature = "proc_macro_lib", since = "1.15.0")]
114#[non_exhaustive]
115#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ::core::fmt::Debug for LexError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "LexError")
}
}Debug)]
116pub struct LexError;
117118#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
119impl fmt::Displayfor LexError {
120fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121f.write_str("cannot parse string into token stream")
122 }
123}
124125#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
126impl error::Errorfor LexError {}
127128#[stable(feature = "proc_macro_lib", since = "1.15.0")]
129impl !Sendfor LexError {}
130#[stable(feature = "proc_macro_lib", since = "1.15.0")]
131impl !Syncfor LexError {}
132133/// Error returned from `TokenStream::expand_expr`.
134#[unstable(feature = "proc_macro_expand", issue = "90765")]
135#[non_exhaustive]
136#[derive(#[automatically_derived]
#[unstable(feature = "proc_macro_expand", issue = "90765")]
impl ::core::fmt::Debug for ExpandError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "ExpandError")
}
}Debug)]
137pub struct ExpandError;
138139#[unstable(feature = "proc_macro_expand", issue = "90765")]
140impl fmt::Displayfor ExpandError {
141fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142f.write_str("macro expansion failed")
143 }
144}
145146#[unstable(feature = "proc_macro_expand", issue = "90765")]
147impl error::Errorfor ExpandError {}
148149#[unstable(feature = "proc_macro_expand", issue = "90765")]
150impl !Sendfor ExpandError {}
151152#[unstable(feature = "proc_macro_expand", issue = "90765")]
153impl !Syncfor ExpandError {}
154155impl TokenStream {
156/// Returns an empty `TokenStream` containing no token trees.
157#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
158pub fn new() -> TokenStream {
159TokenStream(None)
160 }
161162/// Checks if this `TokenStream` is empty.
163#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
164pub fn is_empty(&self) -> bool {
165self.0.as_ref().map(|h| BridgeMethods::ts_is_empty(h)).unwrap_or(true)
166 }
167168/// 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")]
179pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
180let stream = self.0.as_ref().ok_or(ExpandError)?;
181match BridgeMethods::ts_expand_expr(stream) {
182Ok(stream) => Ok(TokenStream(Some(stream))),
183Err(_) => Err(ExpandError),
184 }
185 }
186}
187188/// 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 FromStrfor TokenStream {
197type Err = LexError;
198199fn from_str(src: &str) -> Result<TokenStream, LexError> {
200Ok(TokenStream(Some(BridgeMethods::ts_from_str(src))))
201 }
202}
203204/// 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::Displayfor TokenStream {
217fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218match &self.0 {
219Some(ts) => f.write_fmt(format_args!("{0}", BridgeMethods::ts_to_string(ts)))write!(f, "{}", BridgeMethods::ts_to_string(ts)),
220None => Ok(()),
221 }
222 }
223}
224225/// Prints tokens in a form convenient for debugging.
226#[stable(feature = "proc_macro_lib", since = "1.15.0")]
227impl fmt::Debugfor TokenStream {
228fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229f.write_str("TokenStream ")?;
230f.debug_list().entries(self.clone()).finish()
231 }
232}
233234#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
235impl Defaultfor TokenStream {
236fn default() -> Self {
237TokenStream::new()
238 }
239}
240241#[unstable(feature = "proc_macro_quote", issue = "54722")]
242pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
243244fn tree_to_bridge_tree(
245 tree: TokenTree,
246) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
247match 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}
254255/// Creates a token stream containing a single token tree.
256#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
257impl From<TokenTree> for TokenStream {
258fn from(tree: TokenTree) -> TokenStream {
259TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
260 }
261}
262263/// 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}
274275impl ConcatTreesHelper {
276fn new(capacity: usize) -> Self {
277ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
278 }
279280fn push(&mut self, tree: TokenTree) {
281self.trees.push(tree_to_bridge_tree(tree));
282 }
283284fn build(self) -> TokenStream {
285if self.trees.is_empty() {
286TokenStream(None)
287 } else {
288TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
289 }
290 }
291292fn append_to(self, stream: &mut TokenStream) {
293if self.trees.is_empty() {
294return;
295 }
296stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
297 }
298}
299300/// 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}
305306impl ConcatStreamsHelper {
307fn new(capacity: usize) -> Self {
308ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
309 }
310311fn push(&mut self, stream: TokenStream) {
312if let Some(stream) = stream.0 {
313self.streams.push(stream);
314 }
315 }
316317fn build(mut self) -> TokenStream {
318if self.streams.len() <= 1 {
319TokenStream(self.streams.pop())
320 } else {
321TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
322 }
323 }
324325fn append_to(mut self, stream: &mut TokenStream) {
326if self.streams.is_empty() {
327return;
328 }
329let base = stream.0.take();
330if base.is_none() && self.streams.len() == 1 {
331stream.0 = self.streams.pop();
332 } else {
333stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
334 }
335 }
336}
337338/// 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 {
341fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
342let iter = trees.into_iter();
343let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
344iter.for_each(|tree| builder.push(tree));
345builder.build()
346 }
347}
348349/// 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 {
353fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
354let iter = streams.into_iter();
355let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
356iter.for_each(|stream| builder.push(stream));
357builder.build()
358 }
359}
360361#[stable(feature = "token_stream_extend", since = "1.30.0")]
362impl Extend<TokenTree> for TokenStream {
363fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
364let iter = trees.into_iter();
365let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
366iter.for_each(|tree| builder.push(tree));
367builder.append_to(self);
368 }
369}
370371#[stable(feature = "token_stream_extend", since = "1.30.0")]
372impl Extend<TokenStream> for TokenStream {
373fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
374let iter = streams.into_iter();
375let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
376iter.for_each(|stream| builder.push(stream));
377builder.append_to(self);
378 }
379}
380381macro_rules!extend_items {
382 ($($item:ident)*) => {
383 $(
384#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
385impl Extend<$item> for TokenStream {
386fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
387self.extend(iter.into_iter().map(TokenTree::$item));
388 }
389 }
390 )*
391 };
392}
393394#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Ident> for TokenStream {
fn extend<T: IntoIterator<Item = Ident>>(&mut self, iter: T) {
self.extend(iter.into_iter().map(TokenTree::Ident));
}
}extend_items!(Group Literal Punct Ident);
395396/// Public implementation details for the `TokenStream` type, such as iterators.
397#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
398pub mod token_stream {
399use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
400401/// 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(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for IntoIter {
#[inline]
fn clone(&self) -> IntoIter {
IntoIter(::core::clone::Clone::clone(&self.0))
}
}Clone)]
405 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
406pub struct IntoIter(
407 std::vec::IntoIter<
408 bridge::TokenTree<
409 bridge::client::TokenStream,
410 bridge::client::Span,
411 bridge::client::Symbol,
412 >,
413 >,
414 );
415416#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
417impl Iteratorfor IntoIter {
418type Item = TokenTree;
419420fn next(&mut self) -> Option<TokenTree> {
421self.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 }
428429fn size_hint(&self) -> (usize, Option<usize>) {
430self.0.size_hint()
431 }
432433fn count(self) -> usize {
434self.0.count()
435 }
436 }
437438#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
439impl IntoIteratorfor TokenStream {
440type Item = TokenTree;
441type IntoIter = IntoIter;
442443fn into_iter(self) -> IntoIter {
444IntoIter(
445self.0.map(|v| BridgeMethods::ts_into_trees(v)).unwrap_or_default().into_iter(),
446 )
447 }
448 }
449}
450451/// `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}
463464#[unstable(feature = "proc_macro_internals", issue = "27812")]
465#[doc(hidden)]
466mod quote;
467468/// A region of source code, along with macro expansion information.
469#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
470#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Span { }Copy, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Span {
#[inline]
fn clone(&self) -> Span {
let _: ::core::clone::AssertParamIsClone<bridge::client::Span>;
*self
}
}Clone)]
471pub struct Span(bridge::client::Span);
472473#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
474impl !Sendfor Span {}
475#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
476impl !Syncfor Span {}
477478macro_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")]
483pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
484 Diagnostic::spanned(self, $level, message)
485 }
486 };
487}
488489impl Span {
490/// A span that resolves at the macro definition site.
491#[unstable(feature = "proc_macro_def_site", issue = "54724")]
492pub fn def_site() -> Span {
493Span(bridge::client::Span::def_site())
494 }
495496/// 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")]
501pub fn call_site() -> Span {
502Span(bridge::client::Span::call_site())
503 }
504505/// 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")]
510pub fn mixed_site() -> Span {
511Span(bridge::client::Span::mixed_site())
512 }
513514/// 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")]
517pub fn parent(&self) -> Option<Span> {
518BridgeMethods::span_parent(self.0).map(Span)
519 }
520521/// 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")]
525pub fn source(&self) -> Span {
526Span(BridgeMethods::span_source(self.0))
527 }
528529/// Returns the span's byte position range in the source file.
530#[unstable(feature = "proc_macro_span", issue = "54725")]
531pub fn byte_range(&self) -> Range<usize> {
532BridgeMethods::span_byte_range(self.0)
533 }
534535/// Creates an empty span pointing to directly before this span.
536#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
537pub fn start(&self) -> Span {
538Span(BridgeMethods::span_start(self.0))
539 }
540541/// Creates an empty span pointing to directly after this span.
542#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
543pub fn end(&self) -> Span {
544Span(BridgeMethods::span_end(self.0))
545 }
546547/// 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")]
551pub fn line(&self) -> usize {
552BridgeMethods::span_line(self.0)
553 }
554555/// 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")]
559pub fn column(&self) -> usize {
560BridgeMethods::span_column(self.0)
561 }
562563/// 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")]
568pub fn file(&self) -> String {
569BridgeMethods::span_file(self.0)
570 }
571572/// 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")]
578pub fn local_file(&self) -> Option<PathBuf> {
579BridgeMethods::span_local_file(self.0).map(PathBuf::from)
580 }
581582/// 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")]
586pub fn join(&self, other: Span) -> Option<Span> {
587BridgeMethods::span_join(self.0, other.0).map(Span)
588 }
589590/// 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")]
593pub fn resolved_at(&self, other: Span) -> Span {
594Span(BridgeMethods::span_resolved_at(self.0, other.0))
595 }
596597/// 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")]
600pub fn located_at(&self, other: Span) -> Span {
601other.resolved_at(*self)
602 }
603604/// Compares two spans to see if they're equal.
605#[unstable(feature = "proc_macro_span", issue = "54725")]
606pub fn eq(&self, other: &Span) -> bool {
607self.0 == other.0
608}
609610/// 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")]
618pub fn source_text(&self) -> Option<String> {
619BridgeMethods::span_source_text(self.0)
620 }
621622// Used by the implementation of `Span::quote`
623#[doc(hidden)]
624 #[unstable(feature = "proc_macro_internals", issue = "27812")]
625pub fn save_span(&self) -> usize {
626BridgeMethods::span_save_span(self.0)
627 }
628629// Used by the implementation of `Span::quote`
630#[doc(hidden)]
631 #[unstable(feature = "proc_macro_internals", issue = "27812")]
632pub fn recover_proc_macro_span(id: usize) -> Span {
633Span(BridgeMethods::span_recover_proc_macro_span(id))
634 }
635636String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Error, message);diagnostic_method!(error, Level::Error);
637String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Warning, message);diagnostic_method!(warning, Level::Warning);
638String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Note, message);diagnostic_method!(note, Level::Note);
639String
Self
self
T
message
Diagnostic
Diagnostic::spanned(self, Level::Help, message);diagnostic_method!(help, Level::Help);
640}
641642/// Prints a span in a form convenient for debugging.
643#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
644impl fmt::Debugfor Span {
645fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
646self.0.fmt(f)
647 }
648}
649650/// 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(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for TokenTree {
#[inline]
fn clone(&self) -> TokenTree {
match self {
TokenTree::Group(__self_0) =>
TokenTree::Group(::core::clone::Clone::clone(__self_0)),
TokenTree::Ident(__self_0) =>
TokenTree::Ident(::core::clone::Clone::clone(__self_0)),
TokenTree::Punct(__self_0) =>
TokenTree::Punct(::core::clone::Clone::clone(__self_0)),
TokenTree::Literal(__self_0) =>
TokenTree::Literal(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
653pub enum TokenTree {
654/// A token stream surrounded by bracket delimiters.
655#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
656Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
657/// An identifier.
658#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
659Ident(#[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")]
662Punct(#[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")]
665Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
666}
667668#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
669impl !Sendfor TokenTree {}
670#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
671impl !Syncfor TokenTree {}
672673impl 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")]
677pub fn span(&self) -> Span {
678match *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 }
685686/// 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")]
692pub fn set_span(&mut self, span: Span) {
693match *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}
701702/// Prints token tree in a form convenient for debugging.
703#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
704impl fmt::Debugfor TokenTree {
705fn 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
708match *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}
716717#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
718impl From<Group> for TokenTree {
719fn from(g: Group) -> TokenTree {
720 TokenTree::Group(g)
721 }
722}
723724#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
725impl From<Ident> for TokenTree {
726fn from(g: Ident) -> TokenTree {
727 TokenTree::Ident(g)
728 }
729}
730731#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
732impl From<Punct> for TokenTree {
733fn from(g: Punct) -> TokenTree {
734 TokenTree::Punct(g)
735 }
736}
737738#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
739impl From<Literal> for TokenTree {
740fn from(g: Literal) -> TokenTree {
741 TokenTree::Literal(g)
742 }
743}
744745/// 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::Displayfor TokenTree {
758fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
759match self {
760 TokenTree::Group(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
761 TokenTree::Ident(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
762 TokenTree::Punct(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
763 TokenTree::Literal(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
764 }
765 }
766}
767768/// A delimited token stream.
769///
770/// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
771#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Group {
#[inline]
fn clone(&self) -> Group { Group(::core::clone::Clone::clone(&self.0)) }
}Clone)]
772#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
773pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
774775#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
776impl !Sendfor Group {}
777#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
778impl !Syncfor Group {}
779780/// Describes how a sequence of token trees is delimited.
781#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Delimiter { }Copy, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Delimiter {
#[inline]
fn clone(&self) -> Delimiter { *self }
}Clone, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::fmt::Debug for Delimiter {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Delimiter::Parenthesis => "Parenthesis",
Delimiter::Brace => "Brace",
Delimiter::Bracket => "Bracket",
Delimiter::None => "None",
})
}
}Debug, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::PartialEq for Delimiter {
#[inline]
fn eq(&self, other: &Delimiter) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::Eq for Delimiter {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}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")]
786Parenthesis,
787/// `{ ... }`
788#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789Brace,
790/// `[ ... ]`
791#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
792Bracket,
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")]
811None,
812}
813814impl 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")]
821pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
822Group(bridge::Group {
823delimiter,
824 stream: stream.0,
825 span: bridge::DelimSpan::from_single(Span::call_site().0),
826 })
827 }
828829/// Returns the delimiter of this `Group`
830#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
831pub fn delimiter(&self) -> Delimiter {
832self.0.delimiter
833 }
834835/// 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")]
840pub fn stream(&self) -> TokenStream {
841TokenStream(self.0.stream.clone())
842 }
843844/// 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")]
852pub fn span(&self) -> Span {
853Span(self.0.span.entire)
854 }
855856/// 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")]
863pub fn span_open(&self) -> Span {
864Span(self.0.span.open)
865 }
866867/// 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")]
874pub fn span_close(&self) -> Span {
875Span(self.0.span.close)
876 }
877878/// 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")]
885pub fn set_span(&mut self, span: Span) {
886self.0.span = bridge::DelimSpan::from_single(span.0);
887 }
888}
889890/// 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::Displayfor Group {
895fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
896f.write_fmt(format_args!("{0}",
TokenStream::from(TokenTree::from(self.clone()))))write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))897 }
898}
899900#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
901impl fmt::Debugfor Group {
902fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903f.debug_struct("Group")
904 .field("delimiter", &self.delimiter())
905 .field("stream", &self.stream())
906 .field("span", &self.span())
907 .finish()
908 }
909}
910911/// 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(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Punct {
#[inline]
fn clone(&self) -> Punct { Punct(::core::clone::Clone::clone(&self.0)) }
}Clone)]
917pub struct Punct(bridge::Punct<bridge::client::Span>);
918919#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
920impl !Sendfor Punct {}
921#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
922impl !Syncfor Punct {}
923924/// Indicates whether a `Punct` token can join with the following token
925/// to form a multi-character operator.
926#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Spacing { }Copy, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Spacing {
#[inline]
fn clone(&self) -> Spacing { *self }
}Clone, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::fmt::Debug for Spacing {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Spacing::Joint => "Joint",
Spacing::Alone => "Alone",
})
}
}Debug, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::PartialEq for Spacing {
#[inline]
fn eq(&self, other: &Spacing) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::Eq for Spacing {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}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")]
941Joint,
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")]
949Alone,
950}
951952impl 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")]
960pub fn new(ch: char, spacing: Spacing) -> Punct {
961const LEGAL_CHARS: &[char] = &[
962'=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
963':', '#', '$', '?', '\'',
964 ];
965if !LEGAL_CHARS.contains(&ch) {
966{
::core::panicking::panic_fmt(format_args!("unsupported character `{0:?}`",
ch));
};panic!("unsupported character `{:?}`", ch);
967 }
968Punct(bridge::Punct {
969 ch: chas u8,
970 joint: spacing == Spacing::Joint,
971 span: Span::call_site().0,
972 })
973 }
974975/// Returns the value of this punctuation character as `char`.
976#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
977pub fn as_char(&self) -> char {
978self.0.ch as char979 }
980981/// 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")]
985pub fn spacing(&self) -> Spacing {
986if self.0.joint { Spacing::Joint } else { Spacing::Alone }
987 }
988989/// Returns the span for this punctuation character.
990#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
991pub fn span(&self) -> Span {
992Span(self.0.span)
993 }
994995/// Configure the span for this punctuation character.
996#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
997pub fn set_span(&mut self, span: Span) {
998self.0.span = span.0;
999 }
1000}
10011002/// 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::Displayfor Punct {
1006fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1007f.write_fmt(format_args!("{0}", self.as_char()))write!(f, "{}", self.as_char())1008 }
1009}
10101011#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1012impl fmt::Debugfor Punct {
1013fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1014f.debug_struct("Punct")
1015 .field("ch", &self.as_char())
1016 .field("spacing", &self.spacing())
1017 .field("span", &self.span())
1018 .finish()
1019 }
1020}
10211022#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1023impl PartialEq<char> for Punct {
1024fn eq(&self, rhs: &char) -> bool {
1025self.as_char() == *rhs1026 }
1027}
10281029#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1030impl PartialEq<Punct> for char {
1031fn eq(&self, rhs: &Punct) -> bool {
1032*self == rhs.as_char()
1033 }
1034}
10351036/// An identifier (`ident`).
1037#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Ident {
#[inline]
fn clone(&self) -> Ident { Ident(::core::clone::Clone::clone(&self.0)) }
}Clone)]
1038#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1039pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
10401041impl 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")]
1066pub fn new(string: &str, span: Span) -> Ident {
1067Ident(bridge::Ident {
1068 sym: bridge::client::Symbol::new_ident(string, false),
1069 is_raw: false,
1070 span: span.0,
1071 })
1072 }
10731074/// 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")]
1079pub fn new_raw(string: &str, span: Span) -> Ident {
1080Ident(bridge::Ident {
1081 sym: bridge::client::Symbol::new_ident(string, true),
1082 is_raw: true,
1083 span: span.0,
1084 })
1085 }
10861087/// 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")]
1090pub fn span(&self) -> Span {
1091Span(self.0.span)
1092 }
10931094/// Configures the span of this `Ident`, possibly changing its hygiene context.
1095#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1096pub fn set_span(&mut self, span: Span) {
1097self.0.span = span.0;
1098 }
1099}
11001101/// 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::Displayfor Ident {
1105fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1106if self.0.is_raw {
1107f.write_str("r#")?;
1108 }
1109 fmt::Display::fmt(&self.0.sym, f)
1110 }
1111}
11121113#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1114impl fmt::Debugfor Ident {
1115fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1116f.debug_struct("Ident")
1117 .field("ident", &self.to_string())
1118 .field("span", &self.span())
1119 .finish()
1120 }
1121}
11221123/// 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(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Literal {
#[inline]
fn clone(&self) -> Literal {
Literal(::core::clone::Clone::clone(&self.0))
}
}Clone)]
1128#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1129pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
11301131macro_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")]
1145pub 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}
11551156macro_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")]
1172pub 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}
11821183impl Literal {
1184fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1185Literal(bridge::Literal {
1186kind,
1187 symbol: bridge::client::Symbol::new(value),
1188 suffix: suffix.map(bridge::client::Symbol::new),
1189 span: Span::call_site().0,
1190 })
1191 }
11921193n
Literal
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("isize")),
span: Span::call_site().0,
});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 }12071208n
Literal
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
});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 }12221223/// 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")]
1236pub fn f32_unsuffixed(n: f32) -> Literal {
1237if !n.is_finite() {
1238{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1239 }
1240let mut repr = n.to_string();
1241if !repr.contains('.') {
1242repr.push_str(".0");
1243 }
1244Literal::new(bridge::LitKind::Float, &repr, None)
1245 }
12461247/// 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")]
1261pub fn f32_suffixed(n: f32) -> Literal {
1262if !n.is_finite() {
1263{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1264 }
1265Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1266 }
12671268/// 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")]
1281pub fn f64_unsuffixed(n: f64) -> Literal {
1282if !n.is_finite() {
1283{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1284 }
1285let mut repr = n.to_string();
1286if !repr.contains('.') {
1287repr.push_str(".0");
1288 }
1289Literal::new(bridge::LitKind::Float, &repr, None)
1290 }
12911292/// 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")]
1306pub fn f64_suffixed(n: f64) -> Literal {
1307if !n.is_finite() {
1308{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1309 }
1310Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1311 }
13121313/// String literal.
1314#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1315pub fn string(string: &str) -> Literal {
1316let escape = EscapeOptions {
1317 escape_single_quote: false,
1318 escape_double_quote: true,
1319 escape_nonascii: false,
1320 };
1321let repr = escape_bytes(string.as_bytes(), escape);
1322Literal::new(bridge::LitKind::Str, &repr, None)
1323 }
13241325/// Character literal.
1326#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1327pub fn character(ch: char) -> Literal {
1328let escape = EscapeOptions {
1329 escape_single_quote: true,
1330 escape_double_quote: false,
1331 escape_nonascii: false,
1332 };
1333let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1334Literal::new(bridge::LitKind::Char, &repr, None)
1335 }
13361337/// Byte character literal.
1338#[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1339pub fn byte_character(byte: u8) -> Literal {
1340let escape = EscapeOptions {
1341 escape_single_quote: true,
1342 escape_double_quote: false,
1343 escape_nonascii: true,
1344 };
1345let repr = escape_bytes(&[byte], escape);
1346Literal::new(bridge::LitKind::Byte, &repr, None)
1347 }
13481349/// Byte string literal.
1350#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1351pub fn byte_string(bytes: &[u8]) -> Literal {
1352let escape = EscapeOptions {
1353 escape_single_quote: false,
1354 escape_double_quote: true,
1355 escape_nonascii: true,
1356 };
1357let repr = escape_bytes(bytes, escape);
1358Literal::new(bridge::LitKind::ByteStr, &repr, None)
1359 }
13601361/// C string literal.
1362#[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1363pub fn c_string(string: &CStr) -> Literal {
1364let escape = EscapeOptions {
1365 escape_single_quote: false,
1366 escape_double_quote: true,
1367 escape_nonascii: false,
1368 };
1369let repr = escape_bytes(string.to_bytes(), escape);
1370Literal::new(bridge::LitKind::CStr, &repr, None)
1371 }
13721373/// Returns the span encompassing this literal.
1374#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1375pub fn span(&self) -> Span {
1376Span(self.0.span)
1377 }
13781379/// Configures the span associated for this literal.
1380#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1381pub fn set_span(&mut self, span: Span) {
1382self.0.span = span.0;
1383 }
13841385/// 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")]
1397pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1398BridgeMethods::span_subspan(
1399self.0.span,
1400range.start_bound().cloned(),
1401range.end_bound().cloned(),
1402 )
1403 .map(Span)
1404 }
14051406fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1407self.0.symbol.with(|symbol| match self.0.suffix {
1408Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1409None => f(symbol, ""),
1410 })
1411 }
14121413/// 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.
1417fn 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.
1421fn get_hashes_str(num: u8) -> &'static str {
1422const HASHES: &str = "\
1423 ################################################################\
1424 ################################################################\
1425 ################################################################\
1426 ################################################################\
1427 ";
1428const _: () = if !(HASHES.len() == 256) {
::core::panicking::panic("assertion failed: HASHES.len() == 256")
}assert!(HASHES.len() == 256);
1429&HASHES[..num as usize]
1430 }
14311432self.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) => {
1437let hashes = get_hashes_str(n);
1438f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1439 }
1440 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1441 bridge::LitKind::ByteStrRaw(n) => {
1442let hashes = get_hashes_str(n);
1443f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1444 }
1445 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1446 bridge::LitKind::CStrRaw(n) => {
1447let hashes = get_hashes_str(n);
1448f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1449 }
14501451 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1452f(&[symbol, suffix])
1453 }
1454 })
1455 }
14561457/// Returns the unescaped character value if the current literal is a byte character literal.
1458#[unstable(feature = "proc_macro_value", issue = "136652")]
1459pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1460self.0.symbol.with(|symbol| match self.0.kind {
1461 bridge::LitKind::Char => {
1462unescape_byte(symbol).map_err(ConversionErrorKind::FailedToUnescape)
1463 }
1464_ => Err(ConversionErrorKind::InvalidLiteralKind),
1465 })
1466 }
14671468/// Returns the unescaped character value if the current literal is a character literal.
1469#[unstable(feature = "proc_macro_value", issue = "136652")]
1470pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1471self.0.symbol.with(|symbol| match self.0.kind {
1472 bridge::LitKind::Char => {
1473unescape_char(symbol).map_err(ConversionErrorKind::FailedToUnescape)
1474 }
1475_ => Err(ConversionErrorKind::InvalidLiteralKind),
1476 })
1477 }
14781479/// Returns the unescaped string value if the current literal is a string or a string literal.
1480#[unstable(feature = "proc_macro_value", issue = "136652")]
1481pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1482self.0.symbol.with(|symbol| match self.0.kind {
1483 bridge::LitKind::Str => {
1484if symbol.contains('\\') {
1485let mut buf = String::with_capacity(symbol.len());
1486let 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.
1490unescape_str(
1491symbol,
1492#[inline(always)]
1493|_, c| match c {
1494Ok(c) => buf.push(c),
1495Err(err) => {
1496if err.is_fatal() {
1497error = Some(ConversionErrorKind::FailedToUnescape(err));
1498 }
1499 }
1500 },
1501 );
1502if let Some(error) = error { Err(error) } else { Ok(buf) }
1503 } else {
1504Ok(symbol.to_string())
1505 }
1506 }
1507 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1508_ => Err(ConversionErrorKind::InvalidLiteralKind),
1509 })
1510 }
15111512/// 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")]
1515pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1516self.0.symbol.with(|symbol| match self.0.kind {
1517 bridge::LitKind::CStr => {
1518let mut error = None;
1519let mut buf = Vec::with_capacity(symbol.len());
15201521unescape_c_str(symbol, |_span, res| match res {
1522Ok(MixedUnit::Char(c)) => {
1523buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1524 }
1525Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1526Err(err) => {
1527if err.is_fatal() {
1528error = Some(ConversionErrorKind::FailedToUnescape(err));
1529 }
1530 }
1531 });
1532if let Some(error) = error {
1533Err(error)
1534 } else {
1535buf.push(0);
1536Ok(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.
1543let mut buf = symbol.to_owned().into_bytes();
1544buf.push(0);
1545Ok(buf)
1546 }
1547_ => Err(ConversionErrorKind::InvalidLiteralKind),
1548 })
1549 }
15501551/// 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")]
1554pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1555self.0.symbol.with(|symbol| match self.0.kind {
1556 bridge::LitKind::ByteStr => {
1557let mut buf = Vec::with_capacity(symbol.len());
1558let mut error = None;
15591560unescape_byte_str(symbol, |_, res| match res {
1561Ok(b) => buf.push(b),
1562Err(err) => {
1563if err.is_fatal() {
1564error = Some(ConversionErrorKind::FailedToUnescape(err));
1565 }
1566 }
1567 });
1568if 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>`.
1573Ok(symbol.to_owned().into_bytes())
1574 }
1575_ => Err(ConversionErrorKind::InvalidLiteralKind),
1576 })
1577 }
1578}
15791580/// 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 FromStrfor Literal {
1592type Err = LexError;
15931594fn from_str(src: &str) -> Result<Self, LexError> {
1595match BridgeMethods::literal_from_str(src) {
1596Ok(literal) => Ok(Literal(literal)),
1597Err(()) => Err(LexError),
1598 }
1599 }
1600}
16011602/// 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::Displayfor Literal {
1606fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1607self.with_stringify_parts(|parts| {
1608for part in parts {
1609 fmt::Display::fmt(part, f)?;
1610 }
1611Ok(())
1612 })
1613 }
1614}
16151616#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1617impl fmt::Debugfor Literal {
1618fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1619f.debug_struct("Literal")
1620// format the kind on one line even in {:#?} mode
1621 .field("kind", &format_args!("{0:?}", self.0.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!("{0:?}", self.0.suffix)format_args!("{:?}", self.0.suffix))
1625 .field("span", &self.0.span)
1626 .finish()
1627 }
1628}
16291630#[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 {
1637use std::env::{self, VarError};
1638use std::ffi::OsStr;
1639use std::path::Path;
16401641use crate::BridgeMethods;
16421643/// 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")]
1649pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1650let key: &str = key.as_ref();
1651let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1652BridgeMethods::track_env_var(key, value.as_deref().ok());
1653value1654 }
16551656/// Track a file or directory explicitly.
1657 ///
1658 /// Commonly used for tracking asset preprocessing.
1659#[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1660pub fn path<P: AsRef<Path>>(path: P) {
1661let path: &str = path.as_ref().to_str().unwrap();
1662BridgeMethods::track_path(path);
1663 }
1664}