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(f16)]
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 = "none")]
40#[doc(hidden)]
41pub mod bridge;
4243mod diagnostic;
44mod escape;
45mod to_tokens;
4647use core::convert::From;
48use core::ops::BitOr;
49use std::borrow::Cow;
50use std::ffi::{CStr, CString};
51use std::ops::{Range, RangeBounds};
52use std::path::PathBuf;
53use std::str::FromStr;
54use std::{error, fmt};
5556#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
57pub use diagnostic::{Diagnostic, Level, MultiSpan};
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/// Mostly relating to malformed escape sequences, but also a few other problems.
68#[derive(#[automatically_derived]#[unstable(feature = "proc_macro_value", issue =
"136652")]
impl ::core::fmt::Debug for EscapeError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"EscapeError kind", &&self.kind)
}
}Debug, #[automatically_derived]#[unstable(feature = "proc_macro_value", issue =
"136652")]
impl ::core::marker::StructuralPartialEq for EscapeError { }
#[automatically_derived]#[unstable(feature = "proc_macro_value", issue =
"136652")]
impl ::core::cmp::PartialEq for EscapeError {
#[inline]
fn eq(&self, other: &Self) -> bool { self.kind == other.kind }
}PartialEq, #[automatically_derived]#[unstable(feature = "proc_macro_value", issue =
"136652")]
impl ::core::cmp::Eq for EscapeError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<EscapeErrorKind>;
}
}Eq)]
69#[unstable(feature = "proc_macro_value", issue = "136652")]
70pub struct EscapeError {
71 kind: EscapeErrorKind,
72}
7374#[unstable(feature = "proc_macro_value", issue = "136652")]
75impl error::Errorfor EscapeError {}
7677#[unstable(feature = "proc_macro_value", issue = "136652")]
78impl fmt::Displayfor EscapeError {
79fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 fmt::Display::fmt(&self.kind, f)
81 }
82}
8384#[unstable(feature = "proc_macro_value", issue = "136652")]
85#[doc(hidden)]
86impl From<rustc_literal_escaper::EscapeError> for EscapeError {
87fn from(value: rustc_literal_escaper::EscapeError) -> Self {
88use rustc_literal_escaper::EscapeErroras EE;
8990let kind = match value {
91 EE::ZeroChars => EscapeErrorKind::ZeroChars,
92 EE::MoreThanOneChar => EscapeErrorKind::MoreThanOneChar,
93 EE::LoneSlash => EscapeErrorKind::LoneSlash,
94 EE::InvalidEscape => EscapeErrorKind::InvalidEscape,
95 EE::BareCarriageReturn => EscapeErrorKind::BareCarriageReturn,
96 EE::BareCarriageReturnInRawString => EscapeErrorKind::BareCarriageReturnInRawString,
97 EE::EscapeOnlyChar => EscapeErrorKind::EscapeOnlyChar,
98 EE::TooShortHexEscape => EscapeErrorKind::TooShortHexEscape,
99 EE::InvalidCharInHexEscape => EscapeErrorKind::InvalidCharInHexEscape,
100 EE::OutOfRangeHexEscape => EscapeErrorKind::OutOfRangeHexEscape,
101 EE::NoBraceInUnicodeEscape => EscapeErrorKind::NoBraceInUnicodeEscape,
102 EE::InvalidCharInUnicodeEscape => EscapeErrorKind::InvalidCharInUnicodeEscape,
103 EE::EmptyUnicodeEscape => EscapeErrorKind::EmptyUnicodeEscape,
104 EE::UnclosedUnicodeEscape => EscapeErrorKind::UnclosedUnicodeEscape,
105 EE::LeadingUnderscoreUnicodeEscape => EscapeErrorKind::LeadingUnderscoreUnicodeEscape,
106 EE::OverlongUnicodeEscape => EscapeErrorKind::OverlongUnicodeEscape,
107 EE::LoneSurrogateUnicodeEscape => EscapeErrorKind::LoneSurrogateUnicodeEscape,
108 EE::OutOfRangeUnicodeEscape => EscapeErrorKind::OutOfRangeUnicodeEscape,
109 EE::UnicodeEscapeInByte => EscapeErrorKind::UnicodeEscapeInByte,
110 EE::NonAsciiCharInByte => EscapeErrorKind::NonAsciiCharInByte,
111 EE::NulInCStr => EscapeErrorKind::NulInCStr,
112 EE::UnskippedWhitespaceWarning => EscapeErrorKind::UnskippedWhitespaceWarning,
113 EE::MultipleSkippedLinesWarning => EscapeErrorKind::MultipleSkippedLinesWarning,
114 };
115Self { kind }
116 }
117}
118119/// Mostly relating to malformed escape sequences, but also a few other problems.
120#[derive(#[automatically_derived]impl ::core::fmt::Debug for EscapeErrorKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"ZeroChars MoreThanOneChar LoneSlash InvalidEscape BareCarriageReturn BareCarriageReturnInRawString EscapeOnlyChar TooShortHexEscape InvalidCharInHexEscape OutOfRangeHexEscape NoBraceInUnicodeEscape InvalidCharInUnicodeEscape EmptyUnicodeEscape UnclosedUnicodeEscape LeadingUnderscoreUnicodeEscape OverlongUnicodeEscape LoneSurrogateUnicodeEscape OutOfRangeUnicodeEscape UnicodeEscapeInByte NonAsciiCharInByte NulInCStr UnskippedWhitespaceWarning MultipleSkippedLinesWarning",
match self {
EscapeErrorKind::ZeroChars => 0usize,
EscapeErrorKind::MoreThanOneChar => 10usize,
EscapeErrorKind::LoneSlash => 26usize,
EscapeErrorKind::InvalidEscape => 36usize,
EscapeErrorKind::BareCarriageReturn => 50usize,
EscapeErrorKind::BareCarriageReturnInRawString => 69usize,
EscapeErrorKind::EscapeOnlyChar => 99usize,
EscapeErrorKind::TooShortHexEscape => 114usize,
EscapeErrorKind::InvalidCharInHexEscape => 132usize,
EscapeErrorKind::OutOfRangeHexEscape => 155usize,
EscapeErrorKind::NoBraceInUnicodeEscape => 175usize,
EscapeErrorKind::InvalidCharInUnicodeEscape => 198usize,
EscapeErrorKind::EmptyUnicodeEscape => 225usize,
EscapeErrorKind::UnclosedUnicodeEscape => 244usize,
EscapeErrorKind::LeadingUnderscoreUnicodeEscape => 266usize,
EscapeErrorKind::OverlongUnicodeEscape => 297usize,
EscapeErrorKind::LoneSurrogateUnicodeEscape => 319usize,
EscapeErrorKind::OutOfRangeUnicodeEscape => 346usize,
EscapeErrorKind::UnicodeEscapeInByte => 370usize,
EscapeErrorKind::NonAsciiCharInByte => 390usize,
EscapeErrorKind::NulInCStr => 409usize,
EscapeErrorKind::UnskippedWhitespaceWarning => 419usize,
EscapeErrorKind::MultipleSkippedLinesWarning => 446usize,
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
EscapeErrorKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for EscapeErrorKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for EscapeErrorKind { }Eq)]
121#[non_exhaustive]
122enum EscapeErrorKind {
123/// Expected 1 char, but 0 were found.
124ZeroChars,
125/// Expected 1 char, but more than 1 were found.
126MoreThanOneChar,
127128/// Escaped '\' character without continuation.
129LoneSlash,
130/// Invalid escape character (e.g. '\z').
131InvalidEscape,
132/// Raw '\r' encountered.
133BareCarriageReturn,
134/// Raw '\r' encountered in raw string.
135BareCarriageReturnInRawString,
136/// Unescaped character that was expected to be escaped (e.g. raw '\t').
137EscapeOnlyChar,
138139/// Numeric character escape is too short (e.g. '\x1').
140TooShortHexEscape,
141/// Invalid character in numeric escape (e.g. '\xz')
142InvalidCharInHexEscape,
143/// Character code in numeric escape is non-ascii (e.g. '\xFF').
144OutOfRangeHexEscape,
145146/// '\u' not followed by '{'.
147NoBraceInUnicodeEscape,
148/// Non-hexadecimal value in '\u{..}'.
149InvalidCharInUnicodeEscape,
150/// '\u{}'
151EmptyUnicodeEscape,
152/// No closing brace in '\u{..}', e.g. '\u{12'.
153UnclosedUnicodeEscape,
154/// '\u{_12}'
155LeadingUnderscoreUnicodeEscape,
156/// More than 6 characters in '\u{..}', e.g. '\u{10FFFF_FF}'
157OverlongUnicodeEscape,
158/// Invalid in-bound unicode character code, e.g. '\u{DFFF}'.
159LoneSurrogateUnicodeEscape,
160/// Out of bounds unicode character code, e.g. '\u{FFFFFF}'.
161OutOfRangeUnicodeEscape,
162163/// Unicode escape code in byte literal.
164UnicodeEscapeInByte,
165/// Non-ascii character in byte literal, byte string literal, or raw byte string literal.
166NonAsciiCharInByte,
167168/// `\0` in a C string literal.
169NulInCStr,
170171/// After a line ending with '\', the next line contains whitespace
172 /// characters that are not skipped.
173UnskippedWhitespaceWarning,
174175/// After a line ending with '\', multiple lines are skipped.
176MultipleSkippedLinesWarning,
177}
178179impl error::Errorfor EscapeErrorKind {}
180181impl fmt::Displayfor EscapeErrorKind {
182fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183f.write_str(match self {
184Self::ZeroChars => "zero chars",
185Self::MoreThanOneChar => "more than one char",
186Self::LoneSlash => "lone slash",
187Self::InvalidEscape => "invalid escape",
188Self::BareCarriageReturn => "bare carriage return",
189Self::BareCarriageReturnInRawString => "bare carriage return in raw string",
190Self::EscapeOnlyChar => "escape only char",
191Self::TooShortHexEscape => "too short hex escape",
192Self::InvalidCharInHexEscape => "invalid char in hex escape",
193Self::OutOfRangeHexEscape => "out of range hex escape",
194Self::NoBraceInUnicodeEscape => "no brace in unicode escape",
195Self::InvalidCharInUnicodeEscape => "invalid char in unicode escape",
196Self::EmptyUnicodeEscape => "empty unicode escape",
197Self::UnclosedUnicodeEscape => "unclosed unicode escape",
198Self::LeadingUnderscoreUnicodeEscape => "leading underscore unicode escape",
199Self::OverlongUnicodeEscape => "overlong unicode escape",
200Self::LoneSurrogateUnicodeEscape => "lone surrogate unicode escape",
201Self::OutOfRangeUnicodeEscape => "out of range unicode escape",
202Self::UnicodeEscapeInByte => "unicode escape in byte",
203Self::NonAsciiCharInByte => "non ascii char in byte",
204Self::NulInCStr => "nul in CStr",
205Self::UnskippedWhitespaceWarning => "unskipped whitespace warning",
206Self::MultipleSkippedLinesWarning => "multiple skipped lines warning",
207 })
208 }
209}
210211/// Errors returned when trying to retrieve a literal unescaped value.
212#[unstable(feature = "proc_macro_value", issue = "136652")]
213#[derive(#[automatically_derived]#[unstable(feature = "proc_macro_value", issue =
"136652")]
impl ::core::fmt::Debug for ConversionErrorKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::FailedToUnescape(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"FailedToUnescape", &__self_0),
Self::InvalidLiteralKind =>
::core::fmt::Formatter::write_str(f, "InvalidLiteralKind"),
}
}
}Debug, #[automatically_derived]#[unstable(feature = "proc_macro_value", issue =
"136652")]
impl ::core::marker::StructuralPartialEq for ConversionErrorKind { }
#[automatically_derived]#[unstable(feature = "proc_macro_value", issue =
"136652")]
impl ::core::cmp::PartialEq for ConversionErrorKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::FailedToUnescape(__self_0),
Self::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_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<EscapeError>;
}
}Eq)]
214#[non_exhaustive]
215pub enum ConversionErrorKind {
216/// The literal failed to be escaped, take a look at [`EscapeError`] for more information.
217FailedToUnescape(EscapeError),
218/// Trying to convert a literal with the wrong type.
219InvalidLiteralKind,
220}
221222/// Determines whether proc_macro has been made accessible to the currently
223/// running program.
224///
225/// The proc_macro crate is only intended for use inside the implementation of
226/// procedural macros. All the functions in this crate panic if invoked from
227/// outside of a procedural macro, such as from a build script or unit test or
228/// ordinary Rust binary.
229///
230/// With consideration for Rust libraries that are designed to support both
231/// macro and non-macro use cases, `proc_macro::is_available()` provides a
232/// non-panicking way to detect whether the infrastructure required to use the
233/// API of proc_macro is presently available. Returns true if invoked from
234/// inside of a procedural macro, false if invoked from any other binary.
235#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
236pub fn is_available() -> bool {
237 bridge::client::is_available()
238}
239240/// The main type provided by this crate, representing an abstract stream of
241/// tokens, or, more specifically, a sequence of token trees.
242/// The type provides interfaces for iterating over those token trees and, conversely,
243/// collecting a number of token trees into one stream.
244///
245/// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
246/// and `#[proc_macro_derive]` definitions.
247#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
248#[stable(feature = "proc_macro_lib", since = "1.15.0")]
249#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib", since =
"1.15.0")]
impl ::core::clone::Clone for TokenStream {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
TokenStream(::core::clone::Clone::clone(&self.0))
}
}Clone)]
250pub struct TokenStream(Option<bridge::client::TokenStream>);
251252#[stable(feature = "proc_macro_lib", since = "1.15.0")]
253impl !Sendfor TokenStream {}
254#[stable(feature = "proc_macro_lib", since = "1.15.0")]
255impl !Syncfor TokenStream {}
256257/// Error returned from `TokenStream::from_str`.
258///
259/// The contained error message is explicitly not guaranteed to be stable in any way,
260/// and may change between Rust versions or across compilations.
261#[stable(feature = "proc_macro_lib", since = "1.15.0")]
262#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib", since =
"1.15.0")]
impl ::core::fmt::Debug for LexError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "LexError",
&&self.0)
}
}Debug)]
263pub struct LexError(String);
264265#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
266impl fmt::Displayfor LexError {
267fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268f.write_str(&self.0)
269 }
270}
271272#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
273impl error::Errorfor LexError {}
274275#[stable(feature = "proc_macro_lib", since = "1.15.0")]
276impl !Sendfor LexError {}
277#[stable(feature = "proc_macro_lib", since = "1.15.0")]
278impl !Syncfor LexError {}
279280/// Error returned from `TokenStream::expand_expr`.
281#[unstable(feature = "proc_macro_expand", issue = "90765")]
282#[non_exhaustive]
283#[derive(#[automatically_derived]#[unstable(feature = "proc_macro_expand", issue =
"90765")]
impl ::core::fmt::Debug for ExpandError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "ExpandError")
}
}Debug)]
284pub struct ExpandError;
285286#[unstable(feature = "proc_macro_expand", issue = "90765")]
287impl fmt::Displayfor ExpandError {
288fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289f.write_str("macro expansion failed")
290 }
291}
292293#[unstable(feature = "proc_macro_expand", issue = "90765")]
294impl error::Errorfor ExpandError {}
295296#[unstable(feature = "proc_macro_expand", issue = "90765")]
297impl !Sendfor ExpandError {}
298299#[unstable(feature = "proc_macro_expand", issue = "90765")]
300impl !Syncfor ExpandError {}
301302impl TokenStream {
303/// Returns an empty `TokenStream` containing no token trees.
304#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
305pub fn new() -> TokenStream {
306TokenStream(None)
307 }
308309/// Checks if this `TokenStream` is empty.
310#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
311pub fn is_empty(&self) -> bool {
312self.0.as_ref().map(BridgeMethods::ts_is_empty).unwrap_or(true)
313 }
314315/// Parses this `TokenStream` as an expression and attempts to expand any
316 /// macros within it. Returns the expanded `TokenStream`.
317 ///
318 /// Currently only expressions expanding to literals will succeed, although
319 /// this may be relaxed in the future.
320 ///
321 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
322 /// report an error, failing compilation, and/or return an `Err(..)`. The
323 /// specific behavior for any error condition, and what conditions are
324 /// considered errors, is unspecified and may change in the future.
325#[unstable(feature = "proc_macro_expand", issue = "90765")]
326pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
327let stream = self.0.as_ref().ok_or(ExpandError)?;
328match BridgeMethods::ts_expand_expr(stream) {
329Ok(stream) => Ok(TokenStream(Some(stream))),
330Err(_) => Err(ExpandError),
331 }
332 }
333}
334335/// Attempts to break the string into tokens and parse those tokens into a token stream.
336/// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
337/// or characters not existing in the language.
338/// All tokens in the parsed stream get `Span::call_site()` spans.
339///
340/// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
341/// change these errors into `LexError`s later.
342#[stable(feature = "proc_macro_lib", since = "1.15.0")]
343impl FromStrfor TokenStream {
344type Err = LexError;
345346fn from_str(src: &str) -> Result<TokenStream, LexError> {
347Ok(TokenStream(Some(BridgeMethods::ts_from_str(src).map_err(LexError)?)))
348 }
349}
350351/// Prints the token stream as a string that is supposed to be losslessly convertible back
352/// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
353/// with `Delimiter::None` delimiters and negative numeric literals.
354///
355/// Note: the exact form of the output is subject to change, e.g. there might
356/// be changes in the whitespace used between tokens. Therefore, you should
357/// *not* do any kind of simple substring matching on the output string (as
358/// produced by `to_string`) to implement a proc macro, because that matching
359/// might stop working if such changes happen. Instead, you should work at the
360/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
361/// `TokenTree::Punct`, or `TokenTree::Literal`.
362#[stable(feature = "proc_macro_lib", since = "1.15.0")]
363impl fmt::Displayfor TokenStream {
364fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
365match &self.0 {
366Some(ts) => f.write_fmt(format_args!("{0}", BridgeMethods::ts_to_string(ts)))write!(f, "{}", BridgeMethods::ts_to_string(ts)),
367None => Ok(()),
368 }
369 }
370}
371372/// Prints tokens in a form convenient for debugging.
373#[stable(feature = "proc_macro_lib", since = "1.15.0")]
374impl fmt::Debugfor TokenStream {
375fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376 f.write_str("TokenStream ")?;
377f.debug_list().entries(self.clone()).finish()
378 }
379}
380381#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
382impl Defaultfor TokenStream {
383fn default() -> Self {
384TokenStream::new()
385 }
386}
387388#[unstable(feature = "proc_macro_quote", issue = "54722")]
389pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
390391fn tree_to_bridge_tree(
392 tree: TokenTree,
393) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
394match tree {
395 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
396 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
397 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
398 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
399 }
400}
401402/// Creates a token stream containing a single token tree.
403#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
404impl From<TokenTree> for TokenStream {
405fn from(tree: TokenTree) -> TokenStream {
406TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
407 }
408}
409410/// Non-generic helper for implementing `FromIterator<TokenTree>` and
411/// `Extend<TokenTree>` with less monomorphization in calling crates.
412struct ConcatTreesHelper {
413 trees: Vec<
414 bridge::TokenTree<
415 bridge::client::TokenStream,
416 bridge::client::Span,
417 bridge::client::Symbol,
418 >,
419 >,
420}
421422impl ConcatTreesHelper {
423fn new(capacity: usize) -> Self {
424ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
425 }
426427fn push(&mut self, tree: TokenTree) {
428self.trees.push(tree_to_bridge_tree(tree));
429 }
430431fn build(self) -> TokenStream {
432if self.trees.is_empty() {
433TokenStream(None)
434 } else {
435TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
436 }
437 }
438439fn append_to(self, stream: &mut TokenStream) {
440if self.trees.is_empty() {
441return;
442 }
443stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
444 }
445}
446447/// Non-generic helper for implementing `FromIterator<TokenStream>` and
448/// `Extend<TokenStream>` with less monomorphization in calling crates.
449struct ConcatStreamsHelper {
450 streams: Vec<bridge::client::TokenStream>,
451}
452453impl ConcatStreamsHelper {
454fn new(capacity: usize) -> Self {
455ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
456 }
457458fn push(&mut self, stream: TokenStream) {
459if let Some(stream) = stream.0 {
460self.streams.push(stream);
461 }
462 }
463464fn build(mut self) -> TokenStream {
465if self.streams.len() <= 1 {
466TokenStream(self.streams.pop())
467 } else {
468TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
469 }
470 }
471472fn append_to(mut self, stream: &mut TokenStream) {
473if self.streams.is_empty() {
474return;
475 }
476let base = stream.0.take();
477if base.is_none() && self.streams.len() == 1 {
478stream.0 = self.streams.pop();
479 } else {
480stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
481 }
482 }
483}
484485/// Collects a number of token trees into a single stream.
486#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
487impl FromIterator<TokenTree> for TokenStream {
488fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
489let iter = trees.into_iter();
490let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
491iter.for_each(|tree| builder.push(tree));
492builder.build()
493 }
494}
495496/// A "flattening" operation on token streams, collects token trees
497/// from multiple token streams into a single stream.
498#[stable(feature = "proc_macro_lib", since = "1.15.0")]
499impl FromIterator<TokenStream> for TokenStream {
500fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
501let iter = streams.into_iter();
502let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
503iter.for_each(|stream| builder.push(stream));
504builder.build()
505 }
506}
507508#[stable(feature = "token_stream_extend", since = "1.30.0")]
509impl Extend<TokenTree> for TokenStream {
510fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
511let iter = trees.into_iter();
512let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
513iter.for_each(|tree| builder.push(tree));
514builder.append_to(self);
515 }
516}
517518#[stable(feature = "token_stream_extend", since = "1.30.0")]
519impl Extend<TokenStream> for TokenStream {
520fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
521let iter = streams.into_iter();
522let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
523iter.for_each(|stream| builder.push(stream));
524builder.append_to(self);
525 }
526}
527528macro_rules!extend_items {
529 ($($item:ident)*) => {
530 $(
531#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
532impl Extend<$item> for TokenStream {
533fn extend<I: IntoIterator<Item = $item>>(&mut self, iter: I) {
534self.extend(iter.into_iter().map(TokenTree::$item));
535 }
536 }
537 )*
538 };
539}
540541#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Group> for TokenStream {
fn extend<I: IntoIterator<Item = Group>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(TokenTree::Group));
}
}
#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Literal> for TokenStream {
fn extend<I: IntoIterator<Item = Literal>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(TokenTree::Literal));
}
}
#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Punct> for TokenStream {
fn extend<I: IntoIterator<Item = Punct>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(TokenTree::Punct));
}
}
#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Ident> for TokenStream {
fn extend<I: IntoIterator<Item = Ident>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(TokenTree::Ident));
}
}extend_items!(Group Literal Punct Ident);
542543/// Public implementation details for the `TokenStream` type, such as iterators.
544#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
545pub mod token_stream {
546use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
547548/// An iterator over `TokenStream`'s `TokenTree`s.
549 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
550 /// and returns whole groups as token trees.
551#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::clone::Clone for IntoIter {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { IntoIter(::core::clone::Clone::clone(&self.0)) }
}Clone)]
552 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
553pub struct IntoIter(
554 std::vec::IntoIter<
555 bridge::TokenTree<
556 bridge::client::TokenStream,
557 bridge::client::Span,
558 bridge::client::Symbol,
559 >,
560 >,
561 );
562563#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
564impl Iteratorfor IntoIter {
565type Item = TokenTree;
566567fn next(&mut self) -> Option<TokenTree> {
568self.0.next().map(|tree| match tree {
569 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
570 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
571 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
572 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
573 })
574 }
575576fn size_hint(&self) -> (usize, Option<usize>) {
577self.0.size_hint()
578 }
579580fn count(self) -> usize {
581self.0.count()
582 }
583 }
584585#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
586impl IntoIteratorfor TokenStream {
587type Item = TokenTree;
588type IntoIter = IntoIter;
589590fn into_iter(self) -> IntoIter {
591IntoIter(self.0.map(BridgeMethods::ts_into_trees).unwrap_or_default().into_iter())
592 }
593 }
594}
595596/// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
597/// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
598/// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
599///
600/// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
601/// To quote `$` itself, use `$$`.
602#[unstable(feature = "proc_macro_quote", issue = "54722")]
603#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
604#[rustc_builtin_macro]
605pub macro quote($($t:tt)*) {
606/* compiler built-in */
607}
608609#[unstable(feature = "proc_macro_internals", issue = "none")]
610#[doc(hidden)]
611mod quote;
612613/// A region of source code, along with macro expansion information.
614#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
615#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::marker::Copy for Span { }Copy, #[automatically_derived]#[doc(hidden)]#[stable(feature = "proc_macro_lib2",
since = "1.29.0")]
unsafe impl ::core::clone::TrivialClone for Span { }
#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::clone::Clone for Span {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<bridge::client::Span>;
*self
}
}Clone)]
616pub struct Span(bridge::client::Span);
617618#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
619impl !Sendfor Span {}
620#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
621impl !Syncfor Span {}
622623macro_rules!diagnostic_method {
624 ($name:ident, $level:expr) => {
625/// Creates a new `Diagnostic` with the given `message` at the span
626 /// `self`.
627#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
628pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
629 Diagnostic::spanned(self, $level, message)
630 }
631 };
632}
633634impl Span {
635/// A span that resolves at the macro definition site.
636#[unstable(feature = "proc_macro_def_site", issue = "54724")]
637pub fn def_site() -> Span {
638Span(bridge::client::Span::def_site())
639 }
640641/// The span of the invocation of the current procedural macro.
642 /// Identifiers created with this span will be resolved as if they were written
643 /// directly at the macro call location (call-site hygiene) and other code
644 /// at the macro call site will be able to refer to them as well.
645#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
646pub fn call_site() -> Span {
647Span(bridge::client::Span::call_site())
648 }
649650/// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
651 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
652 /// call site (everything else).
653 /// The span location is taken from the call-site.
654#[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
655pub fn mixed_site() -> Span {
656Span(bridge::client::Span::mixed_site())
657 }
658659/// The `Span` for the tokens in the previous macro expansion from which
660 /// `self` was generated from, if any.
661#[unstable(feature = "proc_macro_span", issue = "54725")]
662pub fn parent(&self) -> Option<Span> {
663BridgeMethods::span_parent(self.0).map(Span)
664 }
665666/// The span for the origin source code that `self` was generated from. If
667 /// this `Span` wasn't generated from other macro expansions then the return
668 /// value is the same as `*self`.
669#[unstable(feature = "proc_macro_span", issue = "54725")]
670pub fn source(&self) -> Span {
671Span(BridgeMethods::span_source(self.0))
672 }
673674/// Returns the span's byte position range in the source file.
675#[unstable(feature = "proc_macro_span", issue = "54725")]
676pub fn byte_range(&self) -> Range<usize> {
677BridgeMethods::span_byte_range(self.0)
678 }
679680/// Creates an empty span pointing to directly before this span.
681#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
682pub fn start(&self) -> Span {
683Span(BridgeMethods::span_start(self.0))
684 }
685686/// Creates an empty span pointing to directly after this span.
687#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
688pub fn end(&self) -> Span {
689Span(BridgeMethods::span_end(self.0))
690 }
691692/// The one-indexed line of the source file where the span starts.
693 ///
694 /// To obtain the line of the span's end, use `span.end().line()`.
695#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
696pub fn line(&self) -> usize {
697BridgeMethods::span_line(self.0)
698 }
699700/// The one-indexed column of the source file where the span starts.
701 ///
702 /// To obtain the column of the span's end, use `span.end().column()`.
703#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
704pub fn column(&self) -> usize {
705BridgeMethods::span_column(self.0)
706 }
707708/// The path to the source file in which this span occurs, for display purposes.
709 ///
710 /// This might not correspond to a valid file system path.
711 /// It might be remapped (e.g. `"/src/lib.rs"`) or an artificial path (e.g. `"<command line>"`).
712#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
713pub fn file(&self) -> String {
714BridgeMethods::span_file(self.0)
715 }
716717/// The path to the source file in which this span occurs on the local file system.
718 ///
719 /// This is the actual path on disk. It is unaffected by path remapping.
720 ///
721 /// This path should not be embedded in the output of the macro; prefer `file()` instead.
722#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
723pub fn local_file(&self) -> Option<PathBuf> {
724BridgeMethods::span_local_file(self.0).map(PathBuf::from)
725 }
726727/// Creates a new span encompassing `self` and `other`.
728 ///
729 /// Returns `None` if `self` and `other` are from different files.
730#[unstable(feature = "proc_macro_span", issue = "54725")]
731pub fn join(&self, other: Span) -> Option<Span> {
732BridgeMethods::span_join(self.0, other.0).map(Span)
733 }
734735/// Creates a new span with the same line/column information as `self` but
736 /// that resolves symbols as though it were at `other`.
737#[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
738pub fn resolved_at(&self, other: Span) -> Span {
739Span(BridgeMethods::span_resolved_at(self.0, other.0))
740 }
741742/// Creates a new span with the same name resolution behavior as `self` but
743 /// with the line/column information of `other`.
744#[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
745pub fn located_at(&self, other: Span) -> Span {
746other.resolved_at(*self)
747 }
748749/// Compares two spans to see if they're equal.
750#[unstable(feature = "proc_macro_span", issue = "54725")]
751pub fn eq(&self, other: &Span) -> bool {
752self.0 == other.0
753}
754755/// Returns the source text behind a span. This preserves the original source
756 /// code, including spaces and comments. It only returns a result if the span
757 /// corresponds to real source code.
758 ///
759 /// Note: The observable result of a macro should only rely on the tokens and
760 /// not on this source text. The result of this function is a best effort to
761 /// be used for diagnostics only.
762#[stable(feature = "proc_macro_source_text", since = "1.66.0")]
763pub fn source_text(&self) -> Option<String> {
764BridgeMethods::span_source_text(self.0)
765 }
766767// Used by the implementation of `Span::quote`
768#[doc(hidden)]
769 #[unstable(feature = "proc_macro_internals", issue = "none")]
770pub fn save_span(&self) -> usize {
771BridgeMethods::span_save_span(self.0)
772 }
773774// Used by the implementation of `Span::quote`
775#[doc(hidden)]
776 #[unstable(feature = "proc_macro_internals", issue = "none")]
777pub fn recover_proc_macro_span(id: usize) -> Span {
778Span(BridgeMethods::span_recover_proc_macro_span(id))
779 }
780781/// Creates a new `Diagnostic` with the given `message` at the span
/// `self`.
#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
pub fn error<T: Into<String>>(self, message: T) -> Diagnostic {
Diagnostic::spanned(self, Level::Error, message)
}diagnostic_method!(error, Level::Error);
782/// Creates a new `Diagnostic` with the given `message` at the span
/// `self`.
#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
pub fn warning<T: Into<String>>(self, message: T) -> Diagnostic {
Diagnostic::spanned(self, Level::Warning, message)
}diagnostic_method!(warning, Level::Warning);
783/// Creates a new `Diagnostic` with the given `message` at the span
/// `self`.
#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
pub fn note<T: Into<String>>(self, message: T) -> Diagnostic {
Diagnostic::spanned(self, Level::Note, message)
}diagnostic_method!(note, Level::Note);
784/// Creates a new `Diagnostic` with the given `message` at the span
/// `self`.
#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
pub fn help<T: Into<String>>(self, message: T) -> Diagnostic {
Diagnostic::spanned(self, Level::Help, message)
}diagnostic_method!(help, Level::Help);
785}
786787/// Prints a span in a form convenient for debugging.
788#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789impl fmt::Debugfor Span {
790fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
791self.0.fmt(f)
792 }
793}
794795/// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
796#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
797#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::clone::Clone for TokenTree {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::Group(__self_0) =>
TokenTree::Group(::core::clone::Clone::clone(__self_0)),
Self::Ident(__self_0) =>
TokenTree::Ident(::core::clone::Clone::clone(__self_0)),
Self::Punct(__self_0) =>
TokenTree::Punct(::core::clone::Clone::clone(__self_0)),
Self::Literal(__self_0) =>
TokenTree::Literal(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
798pub enum TokenTree {
799/// A token stream surrounded by bracket delimiters.
800#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
801Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
802/// An identifier.
803#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
804Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
805/// A single punctuation character (`+`, `,`, `$`, etc.).
806#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
807Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
808/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
809#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
810Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
811}
812813#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
814impl !Sendfor TokenTree {}
815#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
816impl !Syncfor TokenTree {}
817818impl TokenTree {
819/// Returns the span of this tree, delegating to the `span` method of
820 /// the contained token or a delimited stream.
821#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
822pub fn span(&self) -> Span {
823match *self {
824 TokenTree::Group(ref t) => t.span(),
825 TokenTree::Ident(ref t) => t.span(),
826 TokenTree::Punct(ref t) => t.span(),
827 TokenTree::Literal(ref t) => t.span(),
828 }
829 }
830831/// Configures the span for *only this token*.
832 ///
833 /// Note that if this token is a `Group` then this method will not configure
834 /// the span of each of the internal tokens, this will simply delegate to
835 /// the `set_span` method of each variant.
836#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
837pub fn set_span(&mut self, span: Span) {
838match *self {
839 TokenTree::Group(ref mut t) => t.set_span(span),
840 TokenTree::Ident(ref mut t) => t.set_span(span),
841 TokenTree::Punct(ref mut t) => t.set_span(span),
842 TokenTree::Literal(ref mut t) => t.set_span(span),
843 }
844 }
845}
846847/// Prints token tree in a form convenient for debugging.
848#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
849impl fmt::Debugfor TokenTree {
850fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851// Each of these has the name in the struct type in the derived debug,
852 // so don't bother with an extra layer of indirection
853match *self {
854 TokenTree::Group(ref tt) => tt.fmt(f),
855 TokenTree::Ident(ref tt) => tt.fmt(f),
856 TokenTree::Punct(ref tt) => tt.fmt(f),
857 TokenTree::Literal(ref tt) => tt.fmt(f),
858 }
859 }
860}
861862#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
863impl From<Group> for TokenTree {
864fn from(g: Group) -> TokenTree {
865 TokenTree::Group(g)
866 }
867}
868869#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
870impl From<Ident> for TokenTree {
871fn from(g: Ident) -> TokenTree {
872 TokenTree::Ident(g)
873 }
874}
875876#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
877impl From<Punct> for TokenTree {
878fn from(g: Punct) -> TokenTree {
879 TokenTree::Punct(g)
880 }
881}
882883#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
884impl From<Literal> for TokenTree {
885fn from(g: Literal) -> TokenTree {
886 TokenTree::Literal(g)
887 }
888}
889890/// Prints the token tree as a string that is supposed to be losslessly convertible back
891/// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
892/// with `Delimiter::None` delimiters and negative numeric literals.
893///
894/// Note: the exact form of the output is subject to change, e.g. there might
895/// be changes in the whitespace used between tokens. Therefore, you should
896/// *not* do any kind of simple substring matching on the output string (as
897/// produced by `to_string`) to implement a proc macro, because that matching
898/// might stop working if such changes happen. Instead, you should work at the
899/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
900/// `TokenTree::Punct`, or `TokenTree::Literal`.
901#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
902impl fmt::Displayfor TokenTree {
903fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
904match self {
905 TokenTree::Group(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
906 TokenTree::Ident(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
907 TokenTree::Punct(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
908 TokenTree::Literal(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
909 }
910 }
911}
912913/// A delimited token stream.
914///
915/// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
916#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::clone::Clone for Group {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { Group(::core::clone::Clone::clone(&self.0)) }
}Clone)]
917#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
918pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
919920#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
921impl !Sendfor Group {}
922#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
923impl !Syncfor Group {}
924925/// Describes how a sequence of token trees is delimited.
926#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::marker::Copy for Delimiter { }Copy, #[automatically_derived]#[doc(hidden)]#[stable(feature = "proc_macro_lib2",
since = "1.29.0")]
unsafe impl ::core::clone::TrivialClone for Delimiter { }
#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::clone::Clone for Delimiter {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::fmt::Debug for Delimiter {
#[inline]
#[rustc_trivial_field_reads]
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::marker::StructuralPartialEq for Delimiter { }
#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::cmp::PartialEq for Delimiter {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::cmp::Eq for Delimiter { }Eq)]
927#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
928pub enum Delimiter {
929/// `( ... )`
930#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
931Parenthesis,
932/// `{ ... }`
933#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
934Brace,
935/// `[ ... ]`
936#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
937Bracket,
938/// `∅ ... ∅`
939 /// An invisible delimiter, that may, for example, appear around tokens coming from a
940 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
941 /// `$var * 3` where `$var` is `1 + 2`.
942 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
943 ///
944 /// <div class="warning">
945 ///
946 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
947 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
948 /// of a proc_macro macro are preserved, and only in very specific circumstances.
949 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
950 /// operator priorities as indicated above. The other `Delimiter` variants should be used
951 /// instead in this context. This is a rustc bug. For details, see
952 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
953 ///
954 /// </div>
955#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
956None,
957}
958959impl Group {
960/// Creates a new `Group` with the given delimiter and token stream.
961 ///
962 /// This constructor will set the span for this group to
963 /// `Span::call_site()`. To change the span you can use the `set_span`
964 /// method below.
965#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
966pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
967Group(bridge::Group {
968delimiter,
969 stream: stream.0,
970 span: bridge::DelimSpan::from_single(Span::call_site().0),
971 })
972 }
973974/// Returns the delimiter of this `Group`
975#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
976pub fn delimiter(&self) -> Delimiter {
977self.0.delimiter
978 }
979980/// Returns the `TokenStream` of tokens that are delimited in this `Group`.
981 ///
982 /// Note that the returned token stream does not include the delimiter
983 /// returned above.
984#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
985pub fn stream(&self) -> TokenStream {
986TokenStream(self.0.stream.clone())
987 }
988989/// Returns the span for the delimiters of this token stream, spanning the
990 /// entire `Group`.
991 ///
992 /// ```text
993 /// pub fn span(&self) -> Span {
994 /// ^^^^^^^
995 /// ```
996#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
997pub fn span(&self) -> Span {
998Span(self.0.span.entire)
999 }
10001001/// Returns the span pointing to the opening delimiter of this group.
1002 ///
1003 /// ```text
1004 /// pub fn span_open(&self) -> Span {
1005 /// ^
1006 /// ```
1007#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
1008pub fn span_open(&self) -> Span {
1009Span(self.0.span.open)
1010 }
10111012/// Returns the span pointing to the closing delimiter of this group.
1013 ///
1014 /// ```text
1015 /// pub fn span_close(&self) -> Span {
1016 /// ^
1017 /// ```
1018#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
1019pub fn span_close(&self) -> Span {
1020Span(self.0.span.close)
1021 }
10221023/// Configures the span for this `Group`'s delimiters, but not its internal
1024 /// tokens.
1025 ///
1026 /// This method will **not** set the span of all the internal tokens spanned
1027 /// by this group, but rather it will only set the span of the delimiter
1028 /// tokens at the level of the `Group`.
1029#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1030pub fn set_span(&mut self, span: Span) {
1031self.0.span = bridge::DelimSpan::from_single(span.0);
1032 }
1033}
10341035/// Prints the group as a string that should be losslessly convertible back
1036/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
1037/// with `Delimiter::None` delimiters.
1038#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1039impl fmt::Displayfor Group {
1040fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1041f.write_fmt(format_args!("{0}",
TokenStream::from(TokenTree::from(self.clone()))))write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))1042 }
1043}
10441045#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1046impl fmt::Debugfor Group {
1047fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048f.debug_struct("Group")
1049 .field("delimiter", &self.delimiter())
1050 .field("stream", &self.stream())
1051 .field("span", &self.span())
1052 .finish()
1053 }
1054}
10551056/// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
1057///
1058/// Multi-character operators like `+=` are represented as two instances of `Punct` with different
1059/// forms of `Spacing` returned.
1060#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1061#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::clone::Clone for Punct {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { Punct(::core::clone::Clone::clone(&self.0)) }
}Clone)]
1062pub struct Punct(bridge::Punct<bridge::client::Span>);
10631064#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1065impl !Sendfor Punct {}
1066#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1067impl !Syncfor Punct {}
10681069/// Indicates whether a `Punct` token can join with the following token
1070/// to form a multi-character operator.
1071#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::marker::Copy for Spacing { }Copy, #[automatically_derived]#[doc(hidden)]#[stable(feature = "proc_macro_lib2",
since = "1.29.0")]
unsafe impl ::core::clone::TrivialClone for Spacing { }
#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::clone::Clone for Spacing {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::fmt::Debug for Spacing {
#[inline]
#[rustc_trivial_field_reads]
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::marker::StructuralPartialEq for Spacing { }
#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::cmp::PartialEq for Spacing {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::cmp::Eq for Spacing { }Eq)]
1072#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1073pub enum Spacing {
1074/// A `Punct` token can join with the following token to form a multi-character operator.
1075 ///
1076 /// In token streams constructed using proc macro interfaces, `Joint` punctuation tokens can be
1077 /// followed by any other tokens. However, in token streams parsed from source code, the
1078 /// compiler will only set spacing to `Joint` in the following cases.
1079 /// - When a `Punct` is immediately followed by another `Punct` without a whitespace. E.g. `+`
1080 /// is `Joint` in `+=` and `++`.
1081 /// - When a single quote `'` is immediately followed by an identifier without a whitespace.
1082 /// E.g. `'` is `Joint` in `'lifetime`.
1083 ///
1084 /// This list may be extended in the future to enable more token combinations.
1085#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1086Joint,
1087/// A `Punct` token cannot join with the following token to form a multi-character operator.
1088 ///
1089 /// `Alone` punctuation tokens can be followed by any other tokens. In token streams parsed
1090 /// from source code, the compiler will set spacing to `Alone` in all cases not covered by the
1091 /// conditions for `Joint` above. E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`. In
1092 /// particular, tokens not followed by anything will be marked as `Alone`.
1093#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1094Alone,
1095}
10961097impl Punct {
1098/// Creates a new `Punct` from the given character and spacing.
1099 /// The `ch` argument must be a valid punctuation character permitted by the language,
1100 /// otherwise the function will panic.
1101 ///
1102 /// The returned `Punct` will have the default span of `Span::call_site()`
1103 /// which can be further configured with the `set_span` method below.
1104#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1105pub fn new(ch: char, spacing: Spacing) -> Punct {
1106const LEGAL_CHARS: &[char] = &[
1107'=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
1108':', '#', '$', '?', '\'',
1109 ];
1110if !LEGAL_CHARS.contains(&ch) {
1111{
::core::panicking::panic_fmt(format_args!("unsupported character `{0:?}`",
ch));
};panic!("unsupported character `{:?}`", ch);
1112 }
1113Punct(bridge::Punct {
1114 ch: chas u8,
1115 joint: spacing == Spacing::Joint,
1116 span: Span::call_site().0,
1117 })
1118 }
11191120/// Returns the value of this punctuation character as `char`.
1121#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1122pub fn as_char(&self) -> char {
1123self.0.ch as char1124 }
11251126/// Returns the spacing of this punctuation character, indicating whether it can be potentially
1127 /// combined into a multi-character operator with the following token (`Joint`), or whether the
1128 /// operator has definitely ended (`Alone`).
1129#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1130pub fn spacing(&self) -> Spacing {
1131if self.0.joint { Spacing::Joint } else { Spacing::Alone }
1132 }
11331134/// Returns the span for this punctuation character.
1135#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1136pub fn span(&self) -> Span {
1137Span(self.0.span)
1138 }
11391140/// Configure the span for this punctuation character.
1141#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1142pub fn set_span(&mut self, span: Span) {
1143self.0.span = span.0;
1144 }
1145}
11461147/// Prints the punctuation character as a string that should be losslessly convertible
1148/// back into the same character.
1149#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1150impl fmt::Displayfor Punct {
1151fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1152f.write_fmt(format_args!("{0}", self.as_char()))write!(f, "{}", self.as_char())1153 }
1154}
11551156#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1157impl fmt::Debugfor Punct {
1158fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1159f.debug_struct("Punct")
1160 .field("ch", &self.as_char())
1161 .field("spacing", &self.spacing())
1162 .field("span", &self.span())
1163 .finish()
1164 }
1165}
11661167#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1168impl PartialEq<char> for Punct {
1169fn eq(&self, rhs: &char) -> bool {
1170self.as_char() == *rhs1171 }
1172}
11731174#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1175impl PartialEq<Punct> for char {
1176fn eq(&self, rhs: &Punct) -> bool {
1177*self == rhs.as_char()
1178 }
1179}
11801181/// An identifier (`ident`).
1182#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::clone::Clone for Ident {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { Ident(::core::clone::Clone::clone(&self.0)) }
}Clone)]
1183#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1184pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
11851186impl Ident {
1187/// Creates a new `Ident` with the given `string` as well as the specified
1188 /// `span`.
1189 /// The `string` argument must be a valid identifier permitted by the
1190 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1191 ///
1192 /// The constructed identifier will be NFC-normalized. See the [Reference] for more info.
1193 ///
1194 /// Note that `span`, currently in rustc, configures the hygiene information
1195 /// for this identifier.
1196 ///
1197 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1198 /// meaning that identifiers created with this span will be resolved as if they were written
1199 /// directly at the location of the macro call, and other code at the macro call site will be
1200 /// able to refer to them as well.
1201 ///
1202 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1203 /// meaning that identifiers created with this span will be resolved at the location of the
1204 /// macro definition and other code at the macro call site will not be able to refer to them.
1205 ///
1206 /// Due to the current importance of hygiene this constructor, unlike other
1207 /// tokens, requires a `Span` to be specified at construction.
1208 ///
1209 /// [Reference]: https://doc.rust-lang.org/nightly/reference/identifiers.html#r-ident.normalization
1210#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1211pub fn new(string: &str, span: Span) -> Ident {
1212Ident(bridge::Ident {
1213 sym: bridge::client::Symbol::new_ident(string, false),
1214 kind: bridge::IdentKind::Normal,
1215 span: span.0,
1216 })
1217 }
12181219/// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1220 /// The `string` argument be a valid identifier permitted by the language
1221 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1222 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1223#[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1224pub fn new_raw(string: &str, span: Span) -> Ident {
1225Ident(bridge::Ident {
1226 sym: bridge::client::Symbol::new_ident(string, true),
1227 kind: bridge::IdentKind::Raw,
1228 span: span.0,
1229 })
1230 }
12311232/// Returns the span of this `Ident`, encompassing the entire string returned
1233 /// by [`to_string`](ToString::to_string).
1234#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1235pub fn span(&self) -> Span {
1236Span(self.0.span)
1237 }
12381239/// Configures the span of this `Ident`, possibly changing its hygiene context.
1240#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1241pub fn set_span(&mut self, span: Span) {
1242self.0.span = span.0;
1243 }
1244}
12451246/// Prints the identifier as a string that should be losslessly convertible back
1247/// into the same identifier.
1248#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1249impl fmt::Displayfor Ident {
1250fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1251if let Some(prefix) = self.0.kind.prefix() {
1252 f.write_str(prefix)?;
1253 }
1254 fmt::Display::fmt(&self.0.sym, f)
1255 }
1256}
12571258#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1259impl fmt::Debugfor Ident {
1260fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261f.debug_struct("Ident")
1262 .field("ident", &self.to_string())
1263 .field("span", &self.span())
1264 .finish()
1265 }
1266}
12671268/// A literal string (`"hello"`), byte string (`b"hello"`), C string (`c"hello"`),
1269/// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1270/// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1271/// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1272#[derive(#[automatically_derived]#[stable(feature = "proc_macro_lib2", since =
"1.29.0")]
impl ::core::clone::Clone for Literal {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { Literal(::core::clone::Clone::clone(&self.0)) }
}Clone)]
1273#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1274pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
12751276macro_rules!suffixed_int_literals {
1277 ($($name:ident => $kind:ident,)*) => ($(
1278/// Creates a new suffixed integer literal with the specified value.
1279 ///
1280 /// This function will create an integer like `1u32` where the integer
1281 /// value specified is the first part of the token and the integral is
1282 /// also suffixed at the end.
1283 /// Literals created from negative numbers might not survive round-trips through
1284 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1285 ///
1286 /// Literals created through this method have the `Span::call_site()`
1287 /// span by default, which can be configured with the `set_span` method
1288 /// below.
1289#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1290pub fn $name(n: $kind) -> Literal {
1291 Literal(bridge::Literal {
1292 kind: bridge::LitKind::Integer,
1293 symbol: bridge::client::Symbol::new(&n.to_string()),
1294 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1295 span: Span::call_site().0,
1296 })
1297 }
1298 )*)
1299}
13001301macro_rules!unsuffixed_int_literals {
1302 ($($name:ident => $kind:ident,)*) => ($(
1303/// Creates a new unsuffixed integer literal with the specified value.
1304 ///
1305 /// This function will create an integer like `1` where the integer
1306 /// value specified is the first part of the token. No suffix is
1307 /// specified on this token, meaning that invocations like
1308 /// `Literal::i8_unsuffixed(1)` are equivalent to
1309 /// `Literal::u32_unsuffixed(1)`.
1310 /// Literals created from negative numbers might not survive roundtrips through
1311 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1312 ///
1313 /// Literals created through this method have the `Span::call_site()`
1314 /// span by default, which can be configured with the `set_span` method
1315 /// below.
1316#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1317pub fn $name(n: $kind) -> Literal {
1318 Literal(bridge::Literal {
1319 kind: bridge::LitKind::Integer,
1320 symbol: bridge::client::Symbol::new(&n.to_string()),
1321 suffix: None,
1322 span: Span::call_site().0,
1323 })
1324 }
1325 )*)
1326}
13271328macro_rules!integer_values {
1329 ($($nb:ident => $fn_name:ident,)+) => {
1330 $(
1331#[doc = concat!(
1332"Returns the unescaped `",
1333stringify!($nb),
1334"` value if the literal is a `",
1335stringify!($nb),
1336"` or if it's an \"unmarked\" integer which doesn't overflow.")]
1337 #[unstable(feature = "proc_macro_value", issue = "136652")]
1338pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1339if self.0.kind != bridge::LitKind::Integer {
1340return Err(ConversionErrorKind::InvalidLiteralKind);
1341 }
1342self.with_symbol_and_suffix(|symbol, suffix| {
1343match suffix {
1344stringify!($nb) | "" => {
1345let symbol = strip_underscores(symbol);
1346let (number, base) = parse_number(&symbol);
1347$nb::from_str_radix(&number, base as u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1348 }
1349_ => Err(ConversionErrorKind::InvalidLiteralKind),
1350 }
1351 })
1352 }
1353 )+
1354 }
1355}
13561357macro_rules!float_values {
1358 ($($nb:ident => $fn_name:ident,)+) => {
1359 $(
1360#[doc = concat!(
1361"Returns the unescaped `",
1362stringify!($nb),
1363"` value if the literal is a `",
1364stringify!($nb),
1365"` or if it's an \"unmarked\" float which doesn't overflow.")]
1366 #[unstable(feature = "proc_macro_value", issue = "136652")]
1367pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1368if self.0.kind != bridge::LitKind::Float {
1369return Err(ConversionErrorKind::InvalidLiteralKind);
1370 }
1371self.with_symbol_and_suffix(|symbol, suffix| {
1372match suffix {
1373stringify!($nb) | "" => {
1374let number = strip_underscores(symbol);
1375$nb::from_str(&number).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1376 }
1377_ => Err(ConversionErrorKind::InvalidLiteralKind),
1378 }
1379 })
1380 }
1381 )+
1382 }
1383}
13841385impl Literal {
1386fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1387Literal(bridge::Literal {
1388kind,
1389 symbol: bridge::client::Symbol::new(value),
1390 suffix: suffix.map(bridge::client::Symbol::new),
1391 span: Span::call_site().0,
1392 })
1393 }
13941395/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u8_suffixed(n: u8) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("u8")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u16_suffixed(n: u16) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("u16")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u32_suffixed(n: u32) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("u32")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u64_suffixed(n: u64) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("u64")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u128_suffixed(n: u128) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("u128")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn usize_suffixed(n: usize) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("usize")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i8_suffixed(n: i8) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("i8")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i16_suffixed(n: i16) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("i16")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i32_suffixed(n: i32) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("i32")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i64_suffixed(n: i64) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("i64")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i128_suffixed(n: i128) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("i128")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn isize_suffixed(n: isize) -> 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! {
1396 u8_suffixed => u8,
1397 u16_suffixed => u16,
1398 u32_suffixed => u32,
1399 u64_suffixed => u64,
1400 u128_suffixed => u128,
1401 usize_suffixed => usize,
1402 i8_suffixed => i8,
1403 i16_suffixed => i16,
1404 i32_suffixed => i32,
1405 i64_suffixed => i64,
1406 i128_suffixed => i128,
1407 isize_suffixed => isize,
1408 }14091410/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u8_unsuffixed(n: u8) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u16_unsuffixed(n: u16) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u32_unsuffixed(n: u32) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u64_unsuffixed(n: u64) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u128_unsuffixed(n: u128) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn usize_unsuffixed(n: usize) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i8_unsuffixed(n: i8) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i16_unsuffixed(n: i16) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i32_unsuffixed(n: i32) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i64_unsuffixed(n: i64) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i128_unsuffixed(n: i128) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn isize_unsuffixed(n: isize) -> 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! {
1411 u8_unsuffixed => u8,
1412 u16_unsuffixed => u16,
1413 u32_unsuffixed => u32,
1414 u64_unsuffixed => u64,
1415 u128_unsuffixed => u128,
1416 usize_unsuffixed => usize,
1417 i8_unsuffixed => i8,
1418 i16_unsuffixed => i16,
1419 i32_unsuffixed => i32,
1420 i64_unsuffixed => i64,
1421 i128_unsuffixed => i128,
1422 isize_unsuffixed => isize,
1423 }14241425/// Creates a new unsuffixed floating-point literal.
1426 ///
1427 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1428 /// the float's value is emitted directly into the token but no suffix is
1429 /// used, so it may be inferred to be a `f64` later in the compiler.
1430 /// Literals created from negative numbers might not survive roundtrips through
1431 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1432 ///
1433 /// # Panics
1434 ///
1435 /// This function requires that the specified float is finite, for
1436 /// example if it is infinity or NaN this function will panic.
1437#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1438pub fn f32_unsuffixed(n: f32) -> Literal {
1439if !n.is_finite() {
1440{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1441 }
1442let mut repr = n.to_string();
1443if !repr.contains('.') {
1444repr.push_str(".0");
1445 }
1446Literal::new(bridge::LitKind::Float, &repr, None)
1447 }
14481449/// Creates a new suffixed floating-point literal.
1450 ///
1451 /// This constructor will create a literal like `1.0f32` where the value
1452 /// specified is the preceding part of the token and `f32` is the suffix of
1453 /// the token. This token will always be inferred to be an `f32` in the
1454 /// compiler.
1455 /// Literals created from negative numbers might not survive roundtrips through
1456 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1457 ///
1458 /// # Panics
1459 ///
1460 /// This function requires that the specified float is finite, for
1461 /// example if it is infinity or NaN this function will panic.
1462#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1463pub fn f32_suffixed(n: f32) -> Literal {
1464if !n.is_finite() {
1465{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1466 }
1467Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1468 }
14691470/// Creates a new unsuffixed floating-point literal.
1471 ///
1472 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1473 /// the float's value is emitted directly into the token but no suffix is
1474 /// used, so it may be inferred to be a `f64` later in the compiler.
1475 /// Literals created from negative numbers might not survive roundtrips through
1476 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1477 ///
1478 /// # Panics
1479 ///
1480 /// This function requires that the specified float is finite, for
1481 /// example if it is infinity or NaN this function will panic.
1482#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1483pub fn f64_unsuffixed(n: f64) -> Literal {
1484if !n.is_finite() {
1485{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1486 }
1487let mut repr = n.to_string();
1488if !repr.contains('.') {
1489repr.push_str(".0");
1490 }
1491Literal::new(bridge::LitKind::Float, &repr, None)
1492 }
14931494/// Creates a new suffixed floating-point literal.
1495 ///
1496 /// This constructor will create a literal like `1.0f64` where the value
1497 /// specified is the preceding part of the token and `f64` is the suffix of
1498 /// the token. This token will always be inferred to be an `f64` in the
1499 /// compiler.
1500 /// Literals created from negative numbers might not survive roundtrips through
1501 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1502 ///
1503 /// # Panics
1504 ///
1505 /// This function requires that the specified float is finite, for
1506 /// example if it is infinity or NaN this function will panic.
1507#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1508pub fn f64_suffixed(n: f64) -> Literal {
1509if !n.is_finite() {
1510{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1511 }
1512Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1513 }
15141515/// String literal.
1516#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1517pub fn string(string: &str) -> Literal {
1518let escape = EscapeOptions {
1519 escape_single_quote: false,
1520 escape_double_quote: true,
1521 escape_nonascii: false,
1522 };
1523let repr = escape_bytes(string.as_bytes(), escape);
1524Literal::new(bridge::LitKind::Str, &repr, None)
1525 }
15261527/// Character literal.
1528#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1529pub fn character(ch: char) -> Literal {
1530let escape = EscapeOptions {
1531 escape_single_quote: true,
1532 escape_double_quote: false,
1533 escape_nonascii: false,
1534 };
1535let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1536Literal::new(bridge::LitKind::Char, &repr, None)
1537 }
15381539/// Byte character literal.
1540#[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1541pub fn byte_character(byte: u8) -> Literal {
1542let escape = EscapeOptions {
1543 escape_single_quote: true,
1544 escape_double_quote: false,
1545 escape_nonascii: true,
1546 };
1547let repr = escape_bytes(&[byte], escape);
1548Literal::new(bridge::LitKind::Byte, &repr, None)
1549 }
15501551/// Byte string literal.
1552#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1553pub fn byte_string(bytes: &[u8]) -> Literal {
1554let escape = EscapeOptions {
1555 escape_single_quote: false,
1556 escape_double_quote: true,
1557 escape_nonascii: true,
1558 };
1559let repr = escape_bytes(bytes, escape);
1560Literal::new(bridge::LitKind::ByteStr, &repr, None)
1561 }
15621563/// C string literal.
1564#[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1565pub fn c_string(string: &CStr) -> Literal {
1566let escape = EscapeOptions {
1567 escape_single_quote: false,
1568 escape_double_quote: true,
1569 escape_nonascii: false,
1570 };
1571let repr = escape_bytes(string.to_bytes(), escape);
1572Literal::new(bridge::LitKind::CStr, &repr, None)
1573 }
15741575/// Returns the span encompassing this literal.
1576#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1577pub fn span(&self) -> Span {
1578Span(self.0.span)
1579 }
15801581/// Configures the span associated for this literal.
1582#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1583pub fn set_span(&mut self, span: Span) {
1584self.0.span = span.0;
1585 }
15861587/// Returns a `Span` that is a subset of `self.span()` containing only the
1588 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1589 /// span is outside the bounds of `self`.
1590// FIXME(SergioBenitez): check that the byte range starts and ends at a
1591 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1592 // occur elsewhere when the source text is printed.
1593 // FIXME(SergioBenitez): there is no way for the user to know what
1594 // `self.span()` actually maps to, so this method can currently only be
1595 // called blindly. For example, `to_string()` for the character 'c' returns
1596 // "'\u{63}'"; there is no way for the user to know whether the source text
1597 // was 'c' or whether it was '\u{63}'.
1598#[unstable(feature = "proc_macro_span", issue = "54725")]
1599pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1600BridgeMethods::span_subspan(
1601self.0.span,
1602range.start_bound().cloned(),
1603range.end_bound().cloned(),
1604 )
1605 .map(Span)
1606 }
16071608fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1609self.0.symbol.with(|symbol| match self.0.suffix {
1610Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1611None => f(symbol, ""),
1612 })
1613 }
16141615/// Invokes the callback with a `&[&str]` consisting of each part of the
1616 /// literal's representation. This is done to allow the `ToString` and
1617 /// `Display` implementations to borrow references to symbol values, and
1618 /// both be optimized to reduce overhead.
1619fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1620/// Returns a string containing exactly `num` '#' characters.
1621 /// Uses a 256-character source string literal which is always safe to
1622 /// index with a `u8` index.
1623fn get_hashes_str(num: u8) -> &'static str {
1624const HASHES: &str = "\
1625 ################################################################\
1626 ################################################################\
1627 ################################################################\
1628 ################################################################\
1629 ";
1630const _: () = if !(HASHES.len() == 256) {
::core::panicking::panic("assertion failed: HASHES.len() == 256")
}assert!(HASHES.len() == 256);
1631&HASHES[..num as usize]
1632 }
16331634self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1635 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1636 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1637 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1638 bridge::LitKind::StrRaw(n) => {
1639let hashes = get_hashes_str(n);
1640f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1641 }
1642 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1643 bridge::LitKind::ByteStrRaw(n) => {
1644let hashes = get_hashes_str(n);
1645f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1646 }
1647 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1648 bridge::LitKind::CStrRaw(n) => {
1649let hashes = get_hashes_str(n);
1650f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1651 }
16521653 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1654f(&[symbol, suffix])
1655 }
1656 })
1657 }
16581659/// Returns the unescaped character value if the current literal is a byte character literal.
1660#[unstable(feature = "proc_macro_value", issue = "136652")]
1661pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1662self.0.symbol.with(|symbol| match self.0.kind {
1663 bridge::LitKind::Byte => unescape_byte(symbol)
1664 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1665_ => Err(ConversionErrorKind::InvalidLiteralKind),
1666 })
1667 }
16681669/// Returns the unescaped character value if the current literal is a character literal.
1670#[unstable(feature = "proc_macro_value", issue = "136652")]
1671pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1672self.0.symbol.with(|symbol| match self.0.kind {
1673 bridge::LitKind::Char => unescape_char(symbol)
1674 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1675_ => Err(ConversionErrorKind::InvalidLiteralKind),
1676 })
1677 }
16781679/// Returns the unescaped string value if the current literal is a string or a string literal.
1680#[unstable(feature = "proc_macro_value", issue = "136652")]
1681pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1682self.0.symbol.with(|symbol| match self.0.kind {
1683 bridge::LitKind::Str => {
1684if symbol.contains('\\') {
1685let mut buf = String::with_capacity(symbol.len());
1686let mut error = None;
1687// Force-inlining here is aggressive but the closure is
1688 // called on every char in the string, so it can be hot in
1689 // programs with many long strings containing escapes.
1690unescape_str(
1691symbol,
1692#[inline(always)]
1693|_, c| match c {
1694Ok(c) => buf.push(c),
1695Err(err) => {
1696if err.is_fatal() {
1697error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1698 }
1699 }
1700 },
1701 );
1702if let Some(error) = error { Err(error) } else { Ok(buf) }
1703 } else {
1704Ok(symbol.to_string())
1705 }
1706 }
1707 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1708_ => Err(ConversionErrorKind::InvalidLiteralKind),
1709 })
1710 }
17111712/// Returns the unescaped string value if the current literal is a c-string or a c-string
1713 /// literal.
1714#[unstable(feature = "proc_macro_value", issue = "136652")]
1715pub fn cstr_value(&self) -> Result<CString, ConversionErrorKind> {
1716self.0.symbol.with(|symbol| match self.0.kind {
1717 bridge::LitKind::CStr => {
1718let mut error = None;
1719let mut buf = Vec::with_capacity(symbol.len());
17201721unescape_c_str(symbol, |_span, res| match res {
1722Ok(MixedUnit::Char(c)) => {
1723buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1724 }
1725Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1726Err(err) => {
1727if err.is_fatal() {
1728error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1729 }
1730 }
1731 });
1732if let Some(error) = error {
1733Err(error)
1734 } else {
1735buf.push(0);
1736// Safety: The `buf` content was already checked by the compiler when generating
1737 // the literal.
1738unsafe { Ok(CString::from_vec_with_nul_unchecked(buf)) }
1739 }
1740 }
1741 bridge::LitKind::CStrRaw(_) => {
1742// Raw strings have no escapes so we can convert the symbol
1743 // directly to a `Lrc<u8>` after appending the terminating NUL
1744 // char.
1745Ok(CString::new(symbol.to_owned()).expect("invalid cstr literal"))
1746 }
1747_ => Err(ConversionErrorKind::InvalidLiteralKind),
1748 })
1749 }
17501751/// Returns the unescaped string value if the current literal is a byte string or a byte string
1752 /// literal.
1753#[unstable(feature = "proc_macro_value", issue = "136652")]
1754pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1755self.0.symbol.with(|symbol| match self.0.kind {
1756 bridge::LitKind::ByteStr => {
1757let mut buf = Vec::with_capacity(symbol.len());
1758let mut error = None;
17591760unescape_byte_str(symbol, |_, res| match res {
1761Ok(b) => buf.push(b),
1762Err(err) => {
1763if err.is_fatal() {
1764error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1765 }
1766 }
1767 });
1768if let Some(error) = error { Err(error) } else { Ok(buf) }
1769 }
1770 bridge::LitKind::ByteStrRaw(_) => {
1771// Raw strings have no escapes so we can convert the symbol
1772 // directly to a `Lrc<u8>`.
1773Ok(symbol.to_owned().into_bytes())
1774 }
1775_ => Err(ConversionErrorKind::InvalidLiteralKind),
1776 })
1777 }
17781779#[doc =
"Returns the unescaped `u8` value if the literal is a `u8` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn u8_value(&self) -> Result<u8, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"u8" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
u8::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `u16` value if the literal is a `u16` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn u16_value(&self) -> Result<u16, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"u16" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
u16::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `u32` value if the literal is a `u32` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn u32_value(&self) -> Result<u32, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"u32" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
u32::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `u64` value if the literal is a `u64` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn u64_value(&self) -> Result<u64, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"u64" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
u64::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `u128` value if the literal is a `u128` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn u128_value(&self) -> Result<u128, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"u128" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
u128::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `i8` value if the literal is a `i8` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn i8_value(&self) -> Result<i8, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"i8" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
i8::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `i16` value if the literal is a `i16` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn i16_value(&self) -> Result<i16, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"i16" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
i16::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `i32` value if the literal is a `i32` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn i32_value(&self) -> Result<i32, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"i32" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
i32::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `i64` value if the literal is a `i64` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn i64_value(&self) -> Result<i64, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"i64" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
i64::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `i128` value if the literal is a `i128` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn i128_value(&self) -> Result<i128, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"i128" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
i128::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}integer_values! {
1780 u8 => u8_value,
1781 u16 => u16_value,
1782 u32 => u32_value,
1783 u64 => u64_value,
1784 u128 => u128_value,
1785 i8 => i8_value,
1786 i16 => i16_value,
1787 i32 => i32_value,
1788 i64 => i64_value,
1789 i128 => i128_value,
1790 }17911792#[doc =
"Returns the unescaped `f16` value if the literal is a `f16` or if it\'s an \"unmarked\" float which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn f16_value(&self) -> Result<f16, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Float {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"f16" | "" => {
let number = strip_underscores(symbol);
f16::from_str(&number).map_err(|_|
ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `f32` value if the literal is a `f32` or if it\'s an \"unmarked\" float which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn f32_value(&self) -> Result<f32, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Float {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"f32" | "" => {
let number = strip_underscores(symbol);
f32::from_str(&number).map_err(|_|
ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `f64` value if the literal is a `f64` or if it\'s an \"unmarked\" float which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn f64_value(&self) -> Result<f64, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Float {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"f64" | "" => {
let number = strip_underscores(symbol);
f64::from_str(&number).map_err(|_|
ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}float_values! {
1793 f16 => f16_value,
1794 f32 => f32_value,
1795 f64 => f64_value,
1796// FIXME: `f128` doesn't implement `FromStr` for the moment so we cannot obtain it from
1797 // a `&str`. To be uncommented when it's added.
1798 // f128 => f128_value,
1799}1800}
18011802#[repr(u32)]
1803#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for Base { }
#[automatically_derived]impl ::core::cmp::PartialEq for Base {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Base { }Eq)]
1804enum Base {
1805 Decimal = 10,
1806 Binary = 2,
1807 Octal = 8,
1808 Hexadecimal = 16,
1809}
18101811fn parse_number(value: &str) -> (&str, Base) {
1812let mut iter = value.as_bytes().iter().copied();
1813let Some(first_digit) = iter.next() else {
1814return ("0", Base::Decimal);
1815 };
1816let Some(second_digit) = iter.next() else {
1817return (value, Base::Decimal);
1818 };
18191820let mut base = Base::Decimal;
1821if first_digit == b'0' {
1822// Attempt to parse encoding base.
1823match second_digit {
1824b'b' => {
1825base = Base::Binary;
1826 }
1827b'o' => {
1828base = Base::Octal;
1829 }
1830b'x' => {
1831base = Base::Hexadecimal;
1832 }
1833_ => {}
1834 }
1835 }
18361837let offset = if base == Base::Decimal { 0 } else { 2 };
18381839 (&value[offset..], base)
1840}
18411842fn strip_underscores(value_s: &str) -> Cow<'_, str> {
1843let value = value_s.as_bytes();
1844if value.iter().copied().all(|c| c != b'_' && c != b'f') {
1845return Cow::Borrowed(value_s);
1846 }
1847let mut output = String::with_capacity(value.len());
1848for c in value.iter().copied() {
1849if c != b'_' {
1850 output.push(c as char);
1851 }
1852 }
1853 Cow::Owned(output)
1854}
18551856/// Parse a single literal from its stringified representation.
1857///
1858/// In order to parse successfully, the input string must not contain anything
1859/// but the literal token. Specifically, it must not contain whitespace or
1860/// comments in addition to the literal.
1861///
1862/// The resulting literal token will have a `Span::call_site()` span.
1863///
1864/// NOTE: some errors may cause panics instead of returning `LexError`. We
1865/// reserve the right to change these errors into `LexError`s later.
1866#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1867impl FromStrfor Literal {
1868type Err = LexError;
18691870fn from_str(src: &str) -> Result<Self, LexError> {
1871match BridgeMethods::literal_from_str(src) {
1872Ok(literal) => Ok(Literal(literal)),
1873Err(msg) => Err(LexError(msg)),
1874 }
1875 }
1876}
18771878/// Prints the literal as a string that should be losslessly convertible
1879/// back into the same literal (except for possible rounding for floating point literals).
1880#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1881impl fmt::Displayfor Literal {
1882fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1883self.with_stringify_parts(|parts| {
1884for part in parts {
1885 fmt::Display::fmt(part, f)?;
1886 }
1887Ok(())
1888 })
1889 }
1890}
18911892#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1893impl fmt::Debugfor Literal {
1894fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1895f.debug_struct("Literal")
1896// format the kind on one line even in {:#?} mode
1897 .field("kind", &format_args!("{0:?}", self.0.kind)format_args!("{:?}", self.0.kind))
1898 .field("symbol", &self.0.symbol)
1899// format `Some("...")` on one line even in {:#?} mode
1900 .field("suffix", &format_args!("{0:?}", self.0.suffix)format_args!("{:?}", self.0.suffix))
1901 .field("span", &self.0.span)
1902 .finish()
1903 }
1904}
19051906#[unstable(
1907 feature = "proc_macro_tracked_path",
1908 issue = "99515",
1909 implied_by = "proc_macro_tracked_env"
1910)]
1911/// Functionality for adding environment state to the build dependency info.
1912pub mod tracked {
1913use std::env::{self, VarError};
1914use std::ffi::OsStr;
1915use std::path::Path;
19161917use crate::BridgeMethods;
19181919/// Retrieve an environment variable and add it to build dependency info.
1920 /// The build system executing the compiler will know that the variable was accessed during
1921 /// compilation, and will be able to rerun the build when the value of that variable changes.
1922 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1923 /// standard library, except that the argument must be UTF-8.
1924#[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1925pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1926let key: &str = key.as_ref();
1927let value = env::var(key);
1928BridgeMethods::track_env_var(key, value.as_deref().ok());
1929value1930 }
19311932/// Track a file or directory explicitly.
1933 ///
1934 /// Commonly used for tracking asset preprocessing.
1935#[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1936pub fn path<P: AsRef<Path>>(path: P) {
1937let path: &str = path.as_ref().to_str().unwrap();
1938BridgeMethods::track_path(path);
1939 }
1940}