1//! A support library for macro authors when defining new macros.
2//!
3//! This library, provided by the standard distribution, provides the types
4//! consumed in the interfaces of procedurally defined macro definitions such as
5//! function-like macros `#[proc_macro]`, macro attributes `#[proc_macro_attribute]` and
6//! custom derive attributes `#[proc_macro_derive]`.
7//!
8//! See [the book] for more.
9//!
10//! [the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes
1112#![stable(feature = "proc_macro_lib", since = "1.15.0")]
13#![deny(missing_docs)]
14#![doc(
15 html_playground_url = "https://play.rust-lang.org/",
16 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
17 test(no_crate_inject, attr(deny(warnings))),
18 test(attr(allow(dead_code, deprecated, unused_variables, unused_mut)))
19)]
20#![doc(rust_logo)]
21#![feature(rustdoc_internals)]
22#![feature(staged_api)]
23#![feature(allow_internal_unstable)]
24#![feature(decl_macro)]
25#![feature(negative_impls)]
26#![feature(panic_can_unwind)]
27#![feature(restricted_std)]
28#![feature(rustc_attrs)]
29#![feature(extend_one)]
30#![feature(mem_conjure_zst)]
31#![feature(f16)]
32#![recursion_limit = "256"]
33#![allow(internal_features)]
34#![deny(ffi_unwind_calls)]
35#![allow(rustc::internal)] // Can't use FxHashMap when compiled as part of the standard library
36#![warn(rustdoc::unescaped_backticks)]
37#![warn(unreachable_pub)]
38#![deny(unsafe_op_in_unsafe_fn)]
3940#[unstable(feature = "proc_macro_internals", issue = "none")]
41#[doc(hidden)]
42pub mod bridge;
4344mod diagnostic;
45mod escape;
46mod to_tokens;
4748use core::convert::From;
49use core::ops::BitOr;
50use std::borrow::Cow;
51use std::ffi::CStr;
52use std::ops::{Range, RangeBounds};
53use std::path::PathBuf;
54use std::str::FromStr;
55use std::{error, fmt};
5657#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
58pub use diagnostic::{Diagnostic, Level, MultiSpan};
59use rustc_literal_escaper::{
60MixedUnit, unescape_byte, unescape_byte_str, unescape_c_str, unescape_char, unescape_str,
61};
62#[unstable(feature = "proc_macro_totokens", issue = "130977")]
63pub use to_tokens::ToTokens;
6465use crate::bridge::client::Methodsas BridgeMethods;
66use crate::escape::{EscapeOptions, escape_bytes};
6768/// Mostly relating to malformed escape sequences, but also a few other problems.
69#[unstable(feature = "proc_macro_value", issue = "136652")]
70#[derive(#[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::fmt::Debug for EscapeError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
EscapeError::ZeroChars => "ZeroChars",
EscapeError::MoreThanOneChar => "MoreThanOneChar",
EscapeError::LoneSlash => "LoneSlash",
EscapeError::InvalidEscape => "InvalidEscape",
EscapeError::BareCarriageReturn => "BareCarriageReturn",
EscapeError::BareCarriageReturnInRawString =>
"BareCarriageReturnInRawString",
EscapeError::EscapeOnlyChar => "EscapeOnlyChar",
EscapeError::TooShortHexEscape => "TooShortHexEscape",
EscapeError::InvalidCharInHexEscape =>
"InvalidCharInHexEscape",
EscapeError::OutOfRangeHexEscape => "OutOfRangeHexEscape",
EscapeError::NoBraceInUnicodeEscape =>
"NoBraceInUnicodeEscape",
EscapeError::InvalidCharInUnicodeEscape =>
"InvalidCharInUnicodeEscape",
EscapeError::EmptyUnicodeEscape => "EmptyUnicodeEscape",
EscapeError::UnclosedUnicodeEscape => "UnclosedUnicodeEscape",
EscapeError::LeadingUnderscoreUnicodeEscape =>
"LeadingUnderscoreUnicodeEscape",
EscapeError::OverlongUnicodeEscape => "OverlongUnicodeEscape",
EscapeError::LoneSurrogateUnicodeEscape =>
"LoneSurrogateUnicodeEscape",
EscapeError::OutOfRangeUnicodeEscape =>
"OutOfRangeUnicodeEscape",
EscapeError::UnicodeEscapeInByte => "UnicodeEscapeInByte",
EscapeError::NonAsciiCharInByte => "NonAsciiCharInByte",
EscapeError::NulInCStr => "NulInCStr",
EscapeError::UnskippedWhitespaceWarning =>
"UnskippedWhitespaceWarning",
EscapeError::MultipleSkippedLinesWarning =>
"MultipleSkippedLinesWarning",
})
}
}Debug, #[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::PartialEq for EscapeError {
#[inline]
fn eq(&self, other: &EscapeError) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}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) {}
}Eq)]
71#[non_exhaustive]
72pub enum EscapeError {
73/// Expected 1 char, but 0 were found.
74ZeroChars,
75/// Expected 1 char, but more than 1 were found.
76MoreThanOneChar,
7778/// Escaped '\' character without continuation.
79LoneSlash,
80/// Invalid escape character (e.g. '\z').
81InvalidEscape,
82/// Raw '\r' encountered.
83BareCarriageReturn,
84/// Raw '\r' encountered in raw string.
85BareCarriageReturnInRawString,
86/// Unescaped character that was expected to be escaped (e.g. raw '\t').
87EscapeOnlyChar,
8889/// Numeric character escape is too short (e.g. '\x1').
90TooShortHexEscape,
91/// Invalid character in numeric escape (e.g. '\xz')
92InvalidCharInHexEscape,
93/// Character code in numeric escape is non-ascii (e.g. '\xFF').
94OutOfRangeHexEscape,
9596/// '\u' not followed by '{'.
97NoBraceInUnicodeEscape,
98/// Non-hexadecimal value in '\u{..}'.
99InvalidCharInUnicodeEscape,
100/// '\u{}'
101EmptyUnicodeEscape,
102/// No closing brace in '\u{..}', e.g. '\u{12'.
103UnclosedUnicodeEscape,
104/// '\u{_12}'
105LeadingUnderscoreUnicodeEscape,
106/// More than 6 characters in '\u{..}', e.g. '\u{10FFFF_FF}'
107OverlongUnicodeEscape,
108/// Invalid in-bound unicode character code, e.g. '\u{DFFF}'.
109LoneSurrogateUnicodeEscape,
110/// Out of bounds unicode character code, e.g. '\u{FFFFFF}'.
111OutOfRangeUnicodeEscape,
112113/// Unicode escape code in byte literal.
114UnicodeEscapeInByte,
115/// Non-ascii character in byte literal, byte string literal, or raw byte string literal.
116NonAsciiCharInByte,
117118/// `\0` in a C string literal.
119NulInCStr,
120121/// After a line ending with '\', the next line contains whitespace
122 /// characters that are not skipped.
123UnskippedWhitespaceWarning,
124125/// After a line ending with '\', multiple lines are skipped.
126MultipleSkippedLinesWarning,
127}
128129#[unstable(feature = "proc_macro_value", issue = "136652")]
130#[doc(hidden)]
131impl From<rustc_literal_escaper::EscapeError> for EscapeError {
132fn from(value: rustc_literal_escaper::EscapeError) -> Self {
133use rustc_literal_escaper::EscapeErroras EE;
134135match value {
136 EE::ZeroChars => Self::ZeroChars,
137 EE::MoreThanOneChar => Self::MoreThanOneChar,
138 EE::LoneSlash => Self::LoneSlash,
139 EE::InvalidEscape => Self::InvalidEscape,
140 EE::BareCarriageReturn => Self::BareCarriageReturn,
141 EE::BareCarriageReturnInRawString => Self::BareCarriageReturnInRawString,
142 EE::EscapeOnlyChar => Self::EscapeOnlyChar,
143 EE::TooShortHexEscape => Self::TooShortHexEscape,
144 EE::InvalidCharInHexEscape => Self::InvalidCharInHexEscape,
145 EE::OutOfRangeHexEscape => Self::OutOfRangeHexEscape,
146 EE::NoBraceInUnicodeEscape => Self::NoBraceInUnicodeEscape,
147 EE::InvalidCharInUnicodeEscape => Self::InvalidCharInUnicodeEscape,
148 EE::EmptyUnicodeEscape => Self::EmptyUnicodeEscape,
149 EE::UnclosedUnicodeEscape => Self::UnclosedUnicodeEscape,
150 EE::LeadingUnderscoreUnicodeEscape => Self::LeadingUnderscoreUnicodeEscape,
151 EE::OverlongUnicodeEscape => Self::OverlongUnicodeEscape,
152 EE::LoneSurrogateUnicodeEscape => Self::LoneSurrogateUnicodeEscape,
153 EE::OutOfRangeUnicodeEscape => Self::OutOfRangeUnicodeEscape,
154 EE::UnicodeEscapeInByte => Self::UnicodeEscapeInByte,
155 EE::NonAsciiCharInByte => Self::NonAsciiCharInByte,
156 EE::NulInCStr => Self::NulInCStr,
157 EE::UnskippedWhitespaceWarning => Self::UnskippedWhitespaceWarning,
158 EE::MultipleSkippedLinesWarning => Self::MultipleSkippedLinesWarning,
159 }
160 }
161}
162163#[unstable(feature = "proc_macro_value", issue = "136652")]
164impl error::Errorfor EscapeError {}
165166#[unstable(feature = "proc_macro_value", issue = "136652")]
167impl fmt::Displayfor EscapeError {
168fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169f.write_str(match self {
170Self::ZeroChars => "zero chars",
171Self::MoreThanOneChar => "more than one char",
172Self::LoneSlash => "lone slash",
173Self::InvalidEscape => "invalid escape",
174Self::BareCarriageReturn => "bare carriage return",
175Self::BareCarriageReturnInRawString => "bare carriage return in raw string",
176Self::EscapeOnlyChar => "escape only char",
177Self::TooShortHexEscape => "too short hex escape",
178Self::InvalidCharInHexEscape => "invalid char in hex escape",
179Self::OutOfRangeHexEscape => "out of range hex escape",
180Self::NoBraceInUnicodeEscape => "no brace in unicode escape",
181Self::InvalidCharInUnicodeEscape => "invalid char in unicode escape",
182Self::EmptyUnicodeEscape => "empty unicode escape",
183Self::UnclosedUnicodeEscape => "unclosed unicode escape",
184Self::LeadingUnderscoreUnicodeEscape => "leading underscore unicode escape",
185Self::OverlongUnicodeEscape => "overlong unicode escape",
186Self::LoneSurrogateUnicodeEscape => "lone surrogate unicode escape",
187Self::OutOfRangeUnicodeEscape => "out of range unicode escape",
188Self::UnicodeEscapeInByte => "unicode escape in byte",
189Self::NonAsciiCharInByte => "non ascii char in byte",
190Self::NulInCStr => "nul in CStr",
191Self::UnskippedWhitespaceWarning => "unskipped whitespace warning",
192Self::MultipleSkippedLinesWarning => "multiple skipped lines warning",
193 })
194 }
195}
196197/// Errors returned when trying to retrieve a literal unescaped value.
198#[unstable(feature = "proc_macro_value", issue = "136652")]
199#[derive(#[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::fmt::Debug for ConversionErrorKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ConversionErrorKind::FailedToUnescape(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FailedToUnescape", &__self_0),
ConversionErrorKind::InvalidLiteralKind =>
::core::fmt::Formatter::write_str(f, "InvalidLiteralKind"),
}
}
}Debug, #[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::PartialEq for ConversionErrorKind {
#[inline]
fn eq(&self, other: &ConversionErrorKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ConversionErrorKind::FailedToUnescape(__self_0),
ConversionErrorKind::FailedToUnescape(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::Eq for ConversionErrorKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<EscapeError>;
}
}Eq)]
200#[non_exhaustive]
201pub enum ConversionErrorKind {
202/// The literal failed to be escaped, take a look at [`EscapeError`] for more information.
203FailedToUnescape(EscapeError),
204/// Trying to convert a literal with the wrong type.
205InvalidLiteralKind,
206}
207208/// Determines whether proc_macro has been made accessible to the currently
209/// running program.
210///
211/// The proc_macro crate is only intended for use inside the implementation of
212/// procedural macros. All the functions in this crate panic if invoked from
213/// outside of a procedural macro, such as from a build script or unit test or
214/// ordinary Rust binary.
215///
216/// With consideration for Rust libraries that are designed to support both
217/// macro and non-macro use cases, `proc_macro::is_available()` provides a
218/// non-panicking way to detect whether the infrastructure required to use the
219/// API of proc_macro is presently available. Returns true if invoked from
220/// inside of a procedural macro, false if invoked from any other binary.
221#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
222pub fn is_available() -> bool {
223 bridge::client::is_available()
224}
225226/// The main type provided by this crate, representing an abstract stream of
227/// tokens, or, more specifically, a sequence of token trees.
228/// The type provides interfaces for iterating over those token trees and, conversely,
229/// collecting a number of token trees into one stream.
230///
231/// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
232/// and `#[proc_macro_derive]` definitions.
233#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
234#[stable(feature = "proc_macro_lib", since = "1.15.0")]
235#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ::core::clone::Clone for TokenStream {
#[inline]
fn clone(&self) -> TokenStream {
TokenStream(::core::clone::Clone::clone(&self.0))
}
}Clone)]
236pub struct TokenStream(Option<bridge::client::TokenStream>);
237238#[stable(feature = "proc_macro_lib", since = "1.15.0")]
239impl !Sendfor TokenStream {}
240#[stable(feature = "proc_macro_lib", since = "1.15.0")]
241impl !Syncfor TokenStream {}
242243/// Error returned from `TokenStream::from_str`.
244///
245/// The contained error message is explicitly not guaranteed to be stable in any way,
246/// and may change between Rust versions or across compilations.
247#[stable(feature = "proc_macro_lib", since = "1.15.0")]
248#[non_exhaustive]
249#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ::core::fmt::Debug for LexError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "LexError",
&&self.0)
}
}Debug)]
250pub struct LexError(String);
251252#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
253impl fmt::Displayfor LexError {
254fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255f.write_str(&self.0)
256 }
257}
258259#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
260impl error::Errorfor LexError {}
261262#[stable(feature = "proc_macro_lib", since = "1.15.0")]
263impl !Sendfor LexError {}
264#[stable(feature = "proc_macro_lib", since = "1.15.0")]
265impl !Syncfor LexError {}
266267/// Error returned from `TokenStream::expand_expr`.
268#[unstable(feature = "proc_macro_expand", issue = "90765")]
269#[non_exhaustive]
270#[derive(#[automatically_derived]
#[unstable(feature = "proc_macro_expand", issue = "90765")]
impl ::core::fmt::Debug for ExpandError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "ExpandError")
}
}Debug)]
271pub struct ExpandError;
272273#[unstable(feature = "proc_macro_expand", issue = "90765")]
274impl fmt::Displayfor ExpandError {
275fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276f.write_str("macro expansion failed")
277 }
278}
279280#[unstable(feature = "proc_macro_expand", issue = "90765")]
281impl error::Errorfor ExpandError {}
282283#[unstable(feature = "proc_macro_expand", issue = "90765")]
284impl !Sendfor ExpandError {}
285286#[unstable(feature = "proc_macro_expand", issue = "90765")]
287impl !Syncfor ExpandError {}
288289impl TokenStream {
290/// Returns an empty `TokenStream` containing no token trees.
291#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
292pub fn new() -> TokenStream {
293TokenStream(None)
294 }
295296/// Checks if this `TokenStream` is empty.
297#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
298pub fn is_empty(&self) -> bool {
299self.0.as_ref().map(BridgeMethods::ts_is_empty).unwrap_or(true)
300 }
301302/// Parses this `TokenStream` as an expression and attempts to expand any
303 /// macros within it. Returns the expanded `TokenStream`.
304 ///
305 /// Currently only expressions expanding to literals will succeed, although
306 /// this may be relaxed in the future.
307 ///
308 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
309 /// report an error, failing compilation, and/or return an `Err(..)`. The
310 /// specific behavior for any error condition, and what conditions are
311 /// considered errors, is unspecified and may change in the future.
312#[unstable(feature = "proc_macro_expand", issue = "90765")]
313pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
314let stream = self.0.as_ref().ok_or(ExpandError)?;
315match BridgeMethods::ts_expand_expr(stream) {
316Ok(stream) => Ok(TokenStream(Some(stream))),
317Err(_) => Err(ExpandError),
318 }
319 }
320}
321322/// Attempts to break the string into tokens and parse those tokens into a token stream.
323/// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
324/// or characters not existing in the language.
325/// All tokens in the parsed stream get `Span::call_site()` spans.
326///
327/// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
328/// change these errors into `LexError`s later.
329#[stable(feature = "proc_macro_lib", since = "1.15.0")]
330impl FromStrfor TokenStream {
331type Err = LexError;
332333fn from_str(src: &str) -> Result<TokenStream, LexError> {
334Ok(TokenStream(Some(BridgeMethods::ts_from_str(src).map_err(LexError)?)))
335 }
336}
337338/// Prints the token stream as a string that is supposed to be losslessly convertible back
339/// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
340/// with `Delimiter::None` delimiters and negative numeric literals.
341///
342/// Note: the exact form of the output is subject to change, e.g. there might
343/// be changes in the whitespace used between tokens. Therefore, you should
344/// *not* do any kind of simple substring matching on the output string (as
345/// produced by `to_string`) to implement a proc macro, because that matching
346/// might stop working if such changes happen. Instead, you should work at the
347/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
348/// `TokenTree::Punct`, or `TokenTree::Literal`.
349#[stable(feature = "proc_macro_lib", since = "1.15.0")]
350impl fmt::Displayfor TokenStream {
351fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352match &self.0 {
353Some(ts) => f.write_fmt(format_args!("{0}", BridgeMethods::ts_to_string(ts)))write!(f, "{}", BridgeMethods::ts_to_string(ts)),
354None => Ok(()),
355 }
356 }
357}
358359/// Prints tokens in a form convenient for debugging.
360#[stable(feature = "proc_macro_lib", since = "1.15.0")]
361impl fmt::Debugfor TokenStream {
362fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 f.write_str("TokenStream ")?;
364f.debug_list().entries(self.clone()).finish()
365 }
366}
367368#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
369impl Defaultfor TokenStream {
370fn default() -> Self {
371TokenStream::new()
372 }
373}
374375#[unstable(feature = "proc_macro_quote", issue = "54722")]
376pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
377378fn tree_to_bridge_tree(
379 tree: TokenTree,
380) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
381match tree {
382 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
383 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
384 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
385 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
386 }
387}
388389/// Creates a token stream containing a single token tree.
390#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
391impl From<TokenTree> for TokenStream {
392fn from(tree: TokenTree) -> TokenStream {
393TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
394 }
395}
396397/// Non-generic helper for implementing `FromIterator<TokenTree>` and
398/// `Extend<TokenTree>` with less monomorphization in calling crates.
399struct ConcatTreesHelper {
400 trees: Vec<
401 bridge::TokenTree<
402 bridge::client::TokenStream,
403 bridge::client::Span,
404 bridge::client::Symbol,
405 >,
406 >,
407}
408409impl ConcatTreesHelper {
410fn new(capacity: usize) -> Self {
411ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
412 }
413414fn push(&mut self, tree: TokenTree) {
415self.trees.push(tree_to_bridge_tree(tree));
416 }
417418fn build(self) -> TokenStream {
419if self.trees.is_empty() {
420TokenStream(None)
421 } else {
422TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
423 }
424 }
425426fn append_to(self, stream: &mut TokenStream) {
427if self.trees.is_empty() {
428return;
429 }
430stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
431 }
432}
433434/// Non-generic helper for implementing `FromIterator<TokenStream>` and
435/// `Extend<TokenStream>` with less monomorphization in calling crates.
436struct ConcatStreamsHelper {
437 streams: Vec<bridge::client::TokenStream>,
438}
439440impl ConcatStreamsHelper {
441fn new(capacity: usize) -> Self {
442ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
443 }
444445fn push(&mut self, stream: TokenStream) {
446if let Some(stream) = stream.0 {
447self.streams.push(stream);
448 }
449 }
450451fn build(mut self) -> TokenStream {
452if self.streams.len() <= 1 {
453TokenStream(self.streams.pop())
454 } else {
455TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
456 }
457 }
458459fn append_to(mut self, stream: &mut TokenStream) {
460if self.streams.is_empty() {
461return;
462 }
463let base = stream.0.take();
464if base.is_none() && self.streams.len() == 1 {
465stream.0 = self.streams.pop();
466 } else {
467stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
468 }
469 }
470}
471472/// Collects a number of token trees into a single stream.
473#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
474impl FromIterator<TokenTree> for TokenStream {
475fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
476let iter = trees.into_iter();
477let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
478iter.for_each(|tree| builder.push(tree));
479builder.build()
480 }
481}
482483/// A "flattening" operation on token streams, collects token trees
484/// from multiple token streams into a single stream.
485#[stable(feature = "proc_macro_lib", since = "1.15.0")]
486impl FromIterator<TokenStream> for TokenStream {
487fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
488let iter = streams.into_iter();
489let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
490iter.for_each(|stream| builder.push(stream));
491builder.build()
492 }
493}
494495#[stable(feature = "token_stream_extend", since = "1.30.0")]
496impl Extend<TokenTree> for TokenStream {
497fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
498let iter = trees.into_iter();
499let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
500iter.for_each(|tree| builder.push(tree));
501builder.append_to(self);
502 }
503}
504505#[stable(feature = "token_stream_extend", since = "1.30.0")]
506impl Extend<TokenStream> for TokenStream {
507fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
508let iter = streams.into_iter();
509let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
510iter.for_each(|stream| builder.push(stream));
511builder.append_to(self);
512 }
513}
514515macro_rules!extend_items {
516 ($($item:ident)*) => {
517 $(
518#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
519impl Extend<$item> for TokenStream {
520fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
521self.extend(iter.into_iter().map(TokenTree::$item));
522 }
523 }
524 )*
525 };
526}
527528#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Ident> for TokenStream {
fn extend<T: IntoIterator<Item = Ident>>(&mut self, iter: T) {
self.extend(iter.into_iter().map(TokenTree::Ident));
}
}extend_items!(Group Literal Punct Ident);
529530/// Public implementation details for the `TokenStream` type, such as iterators.
531#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
532pub mod token_stream {
533use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
534535/// An iterator over `TokenStream`'s `TokenTree`s.
536 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
537 /// and returns whole groups as token trees.
538#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for IntoIter {
#[inline]
fn clone(&self) -> IntoIter {
IntoIter(::core::clone::Clone::clone(&self.0))
}
}Clone)]
539 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
540pub struct IntoIter(
541 std::vec::IntoIter<
542 bridge::TokenTree<
543 bridge::client::TokenStream,
544 bridge::client::Span,
545 bridge::client::Symbol,
546 >,
547 >,
548 );
549550#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
551impl Iteratorfor IntoIter {
552type Item = TokenTree;
553554fn next(&mut self) -> Option<TokenTree> {
555self.0.next().map(|tree| match tree {
556 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
557 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
558 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
559 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
560 })
561 }
562563fn size_hint(&self) -> (usize, Option<usize>) {
564self.0.size_hint()
565 }
566567fn count(self) -> usize {
568self.0.count()
569 }
570 }
571572#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
573impl IntoIteratorfor TokenStream {
574type Item = TokenTree;
575type IntoIter = IntoIter;
576577fn into_iter(self) -> IntoIter {
578IntoIter(self.0.map(BridgeMethods::ts_into_trees).unwrap_or_default().into_iter())
579 }
580 }
581}
582583/// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
584/// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
585/// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
586///
587/// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
588/// To quote `$` itself, use `$$`.
589#[unstable(feature = "proc_macro_quote", issue = "54722")]
590#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
591#[rustc_builtin_macro]
592pub macro quote($($t:tt)*) {
593/* compiler built-in */
594}
595596#[unstable(feature = "proc_macro_internals", issue = "none")]
597#[doc(hidden)]
598mod quote;
599600/// A region of source code, along with macro expansion information.
601#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
602#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Span { }Copy, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Span {
#[inline]
fn clone(&self) -> Span {
let _: ::core::clone::AssertParamIsClone<bridge::client::Span>;
*self
}
}Clone)]
603pub struct Span(bridge::client::Span);
604605#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
606impl !Sendfor Span {}
607#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
608impl !Syncfor Span {}
609610macro_rules!diagnostic_method {
611 ($name:ident, $level:expr) => {
612/// Creates a new `Diagnostic` with the given `message` at the span
613 /// `self`.
614#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
615pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
616 Diagnostic::spanned(self, $level, message)
617 }
618 };
619}
620621impl Span {
622/// A span that resolves at the macro definition site.
623#[unstable(feature = "proc_macro_def_site", issue = "54724")]
624pub fn def_site() -> Span {
625Span(bridge::client::Span::def_site())
626 }
627628/// The span of the invocation of the current procedural macro.
629 /// Identifiers created with this span will be resolved as if they were written
630 /// directly at the macro call location (call-site hygiene) and other code
631 /// at the macro call site will be able to refer to them as well.
632#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
633pub fn call_site() -> Span {
634Span(bridge::client::Span::call_site())
635 }
636637/// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
638 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
639 /// call site (everything else).
640 /// The span location is taken from the call-site.
641#[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
642pub fn mixed_site() -> Span {
643Span(bridge::client::Span::mixed_site())
644 }
645646/// The `Span` for the tokens in the previous macro expansion from which
647 /// `self` was generated from, if any.
648#[unstable(feature = "proc_macro_span", issue = "54725")]
649pub fn parent(&self) -> Option<Span> {
650BridgeMethods::span_parent(self.0).map(Span)
651 }
652653/// The span for the origin source code that `self` was generated from. If
654 /// this `Span` wasn't generated from other macro expansions then the return
655 /// value is the same as `*self`.
656#[unstable(feature = "proc_macro_span", issue = "54725")]
657pub fn source(&self) -> Span {
658Span(BridgeMethods::span_source(self.0))
659 }
660661/// Returns the span's byte position range in the source file.
662#[unstable(feature = "proc_macro_span", issue = "54725")]
663pub fn byte_range(&self) -> Range<usize> {
664BridgeMethods::span_byte_range(self.0)
665 }
666667/// Creates an empty span pointing to directly before this span.
668#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
669pub fn start(&self) -> Span {
670Span(BridgeMethods::span_start(self.0))
671 }
672673/// Creates an empty span pointing to directly after this span.
674#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
675pub fn end(&self) -> Span {
676Span(BridgeMethods::span_end(self.0))
677 }
678679/// The one-indexed line of the source file where the span starts.
680 ///
681 /// To obtain the line of the span's end, use `span.end().line()`.
682#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
683pub fn line(&self) -> usize {
684BridgeMethods::span_line(self.0)
685 }
686687/// The one-indexed column of the source file where the span starts.
688 ///
689 /// To obtain the column of the span's end, use `span.end().column()`.
690#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
691pub fn column(&self) -> usize {
692BridgeMethods::span_column(self.0)
693 }
694695/// The path to the source file in which this span occurs, for display purposes.
696 ///
697 /// This might not correspond to a valid file system path.
698 /// It might be remapped (e.g. `"/src/lib.rs"`) or an artificial path (e.g. `"<command line>"`).
699#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
700pub fn file(&self) -> String {
701BridgeMethods::span_file(self.0)
702 }
703704/// The path to the source file in which this span occurs on the local file system.
705 ///
706 /// This is the actual path on disk. It is unaffected by path remapping.
707 ///
708 /// This path should not be embedded in the output of the macro; prefer `file()` instead.
709#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
710pub fn local_file(&self) -> Option<PathBuf> {
711BridgeMethods::span_local_file(self.0).map(PathBuf::from)
712 }
713714/// Creates a new span encompassing `self` and `other`.
715 ///
716 /// Returns `None` if `self` and `other` are from different files.
717#[unstable(feature = "proc_macro_span", issue = "54725")]
718pub fn join(&self, other: Span) -> Option<Span> {
719BridgeMethods::span_join(self.0, other.0).map(Span)
720 }
721722/// Creates a new span with the same line/column information as `self` but
723 /// that resolves symbols as though it were at `other`.
724#[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
725pub fn resolved_at(&self, other: Span) -> Span {
726Span(BridgeMethods::span_resolved_at(self.0, other.0))
727 }
728729/// Creates a new span with the same name resolution behavior as `self` but
730 /// with the line/column information of `other`.
731#[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
732pub fn located_at(&self, other: Span) -> Span {
733other.resolved_at(*self)
734 }
735736/// Compares two spans to see if they're equal.
737#[unstable(feature = "proc_macro_span", issue = "54725")]
738pub fn eq(&self, other: &Span) -> bool {
739self.0 == other.0
740}
741742/// Returns the source text behind a span. This preserves the original source
743 /// code, including spaces and comments. It only returns a result if the span
744 /// corresponds to real source code.
745 ///
746 /// Note: The observable result of a macro should only rely on the tokens and
747 /// not on this source text. The result of this function is a best effort to
748 /// be used for diagnostics only.
749#[stable(feature = "proc_macro_source_text", since = "1.66.0")]
750pub fn source_text(&self) -> Option<String> {
751BridgeMethods::span_source_text(self.0)
752 }
753754// Used by the implementation of `Span::quote`
755#[doc(hidden)]
756 #[unstable(feature = "proc_macro_internals", issue = "none")]
757pub fn save_span(&self) -> usize {
758BridgeMethods::span_save_span(self.0)
759 }
760761// Used by the implementation of `Span::quote`
762#[doc(hidden)]
763 #[unstable(feature = "proc_macro_internals", issue = "none")]
764pub fn recover_proc_macro_span(id: usize) -> Span {
765Span(BridgeMethods::span_recover_proc_macro_span(id))
766 }
767768/// 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);
769/// 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);
770/// 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);
771/// 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);
772}
773774/// Prints a span in a form convenient for debugging.
775#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
776impl fmt::Debugfor Span {
777fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778self.0.fmt(f)
779 }
780}
781782/// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
783#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
784#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for TokenTree {
#[inline]
fn clone(&self) -> TokenTree {
match self {
TokenTree::Group(__self_0) =>
TokenTree::Group(::core::clone::Clone::clone(__self_0)),
TokenTree::Ident(__self_0) =>
TokenTree::Ident(::core::clone::Clone::clone(__self_0)),
TokenTree::Punct(__self_0) =>
TokenTree::Punct(::core::clone::Clone::clone(__self_0)),
TokenTree::Literal(__self_0) =>
TokenTree::Literal(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
785pub enum TokenTree {
786/// A token stream surrounded by bracket delimiters.
787#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
788Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
789/// An identifier.
790#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
791Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
792/// A single punctuation character (`+`, `,`, `$`, etc.).
793#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
794Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
795/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
796#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
797Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
798}
799800#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
801impl !Sendfor TokenTree {}
802#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
803impl !Syncfor TokenTree {}
804805impl TokenTree {
806/// Returns the span of this tree, delegating to the `span` method of
807 /// the contained token or a delimited stream.
808#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
809pub fn span(&self) -> Span {
810match *self {
811 TokenTree::Group(ref t) => t.span(),
812 TokenTree::Ident(ref t) => t.span(),
813 TokenTree::Punct(ref t) => t.span(),
814 TokenTree::Literal(ref t) => t.span(),
815 }
816 }
817818/// Configures the span for *only this token*.
819 ///
820 /// Note that if this token is a `Group` then this method will not configure
821 /// the span of each of the internal tokens, this will simply delegate to
822 /// the `set_span` method of each variant.
823#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
824pub fn set_span(&mut self, span: Span) {
825match *self {
826 TokenTree::Group(ref mut t) => t.set_span(span),
827 TokenTree::Ident(ref mut t) => t.set_span(span),
828 TokenTree::Punct(ref mut t) => t.set_span(span),
829 TokenTree::Literal(ref mut t) => t.set_span(span),
830 }
831 }
832}
833834/// Prints token tree in a form convenient for debugging.
835#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
836impl fmt::Debugfor TokenTree {
837fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838// Each of these has the name in the struct type in the derived debug,
839 // so don't bother with an extra layer of indirection
840match *self {
841 TokenTree::Group(ref tt) => tt.fmt(f),
842 TokenTree::Ident(ref tt) => tt.fmt(f),
843 TokenTree::Punct(ref tt) => tt.fmt(f),
844 TokenTree::Literal(ref tt) => tt.fmt(f),
845 }
846 }
847}
848849#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
850impl From<Group> for TokenTree {
851fn from(g: Group) -> TokenTree {
852 TokenTree::Group(g)
853 }
854}
855856#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
857impl From<Ident> for TokenTree {
858fn from(g: Ident) -> TokenTree {
859 TokenTree::Ident(g)
860 }
861}
862863#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
864impl From<Punct> for TokenTree {
865fn from(g: Punct) -> TokenTree {
866 TokenTree::Punct(g)
867 }
868}
869870#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
871impl From<Literal> for TokenTree {
872fn from(g: Literal) -> TokenTree {
873 TokenTree::Literal(g)
874 }
875}
876877/// Prints the token tree as a string that is supposed to be losslessly convertible back
878/// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
879/// with `Delimiter::None` delimiters and negative numeric literals.
880///
881/// Note: the exact form of the output is subject to change, e.g. there might
882/// be changes in the whitespace used between tokens. Therefore, you should
883/// *not* do any kind of simple substring matching on the output string (as
884/// produced by `to_string`) to implement a proc macro, because that matching
885/// might stop working if such changes happen. Instead, you should work at the
886/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
887/// `TokenTree::Punct`, or `TokenTree::Literal`.
888#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
889impl fmt::Displayfor TokenTree {
890fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
891match self {
892 TokenTree::Group(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
893 TokenTree::Ident(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
894 TokenTree::Punct(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
895 TokenTree::Literal(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
896 }
897 }
898}
899900/// A delimited token stream.
901///
902/// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
903#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Group {
#[inline]
fn clone(&self) -> Group { Group(::core::clone::Clone::clone(&self.0)) }
}Clone)]
904#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
905pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
906907#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
908impl !Sendfor Group {}
909#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
910impl !Syncfor Group {}
911912/// Describes how a sequence of token trees is delimited.
913#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Delimiter { }Copy, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Delimiter {
#[inline]
fn clone(&self) -> Delimiter { *self }
}Clone, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::fmt::Debug for Delimiter {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Delimiter::Parenthesis => "Parenthesis",
Delimiter::Brace => "Brace",
Delimiter::Bracket => "Bracket",
Delimiter::None => "None",
})
}
}Debug, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::PartialEq for Delimiter {
#[inline]
fn eq(&self, other: &Delimiter) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::Eq for Delimiter {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
914#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
915pub enum Delimiter {
916/// `( ... )`
917#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
918Parenthesis,
919/// `{ ... }`
920#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
921Brace,
922/// `[ ... ]`
923#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
924Bracket,
925/// `∅ ... ∅`
926 /// An invisible delimiter, that may, for example, appear around tokens coming from a
927 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
928 /// `$var * 3` where `$var` is `1 + 2`.
929 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
930 ///
931 /// <div class="warning">
932 ///
933 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
934 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
935 /// of a proc_macro macro are preserved, and only in very specific circumstances.
936 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
937 /// operator priorities as indicated above. The other `Delimiter` variants should be used
938 /// instead in this context. This is a rustc bug. For details, see
939 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
940 ///
941 /// </div>
942#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
943None,
944}
945946impl Group {
947/// Creates a new `Group` with the given delimiter and token stream.
948 ///
949 /// This constructor will set the span for this group to
950 /// `Span::call_site()`. To change the span you can use the `set_span`
951 /// method below.
952#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
953pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
954Group(bridge::Group {
955delimiter,
956 stream: stream.0,
957 span: bridge::DelimSpan::from_single(Span::call_site().0),
958 })
959 }
960961/// Returns the delimiter of this `Group`
962#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
963pub fn delimiter(&self) -> Delimiter {
964self.0.delimiter
965 }
966967/// Returns the `TokenStream` of tokens that are delimited in this `Group`.
968 ///
969 /// Note that the returned token stream does not include the delimiter
970 /// returned above.
971#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
972pub fn stream(&self) -> TokenStream {
973TokenStream(self.0.stream.clone())
974 }
975976/// Returns the span for the delimiters of this token stream, spanning the
977 /// entire `Group`.
978 ///
979 /// ```text
980 /// pub fn span(&self) -> Span {
981 /// ^^^^^^^
982 /// ```
983#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
984pub fn span(&self) -> Span {
985Span(self.0.span.entire)
986 }
987988/// Returns the span pointing to the opening delimiter of this group.
989 ///
990 /// ```text
991 /// pub fn span_open(&self) -> Span {
992 /// ^
993 /// ```
994#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
995pub fn span_open(&self) -> Span {
996Span(self.0.span.open)
997 }
998999/// Returns the span pointing to the closing delimiter of this group.
1000 ///
1001 /// ```text
1002 /// pub fn span_close(&self) -> Span {
1003 /// ^
1004 /// ```
1005#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
1006pub fn span_close(&self) -> Span {
1007Span(self.0.span.close)
1008 }
10091010/// Configures the span for this `Group`'s delimiters, but not its internal
1011 /// tokens.
1012 ///
1013 /// This method will **not** set the span of all the internal tokens spanned
1014 /// by this group, but rather it will only set the span of the delimiter
1015 /// tokens at the level of the `Group`.
1016#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1017pub fn set_span(&mut self, span: Span) {
1018self.0.span = bridge::DelimSpan::from_single(span.0);
1019 }
1020}
10211022/// Prints the group as a string that should be losslessly convertible back
1023/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
1024/// with `Delimiter::None` delimiters.
1025#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1026impl fmt::Displayfor Group {
1027fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1028f.write_fmt(format_args!("{0}",
TokenStream::from(TokenTree::from(self.clone()))))write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))1029 }
1030}
10311032#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1033impl fmt::Debugfor Group {
1034fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1035f.debug_struct("Group")
1036 .field("delimiter", &self.delimiter())
1037 .field("stream", &self.stream())
1038 .field("span", &self.span())
1039 .finish()
1040 }
1041}
10421043/// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
1044///
1045/// Multi-character operators like `+=` are represented as two instances of `Punct` with different
1046/// forms of `Spacing` returned.
1047#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1048#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Punct {
#[inline]
fn clone(&self) -> Punct { Punct(::core::clone::Clone::clone(&self.0)) }
}Clone)]
1049pub struct Punct(bridge::Punct<bridge::client::Span>);
10501051#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1052impl !Sendfor Punct {}
1053#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1054impl !Syncfor Punct {}
10551056/// Indicates whether a `Punct` token can join with the following token
1057/// to form a multi-character operator.
1058#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Spacing { }Copy, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Spacing {
#[inline]
fn clone(&self) -> Spacing { *self }
}Clone, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::fmt::Debug for Spacing {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Spacing::Joint => "Joint",
Spacing::Alone => "Alone",
})
}
}Debug, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::PartialEq for Spacing {
#[inline]
fn eq(&self, other: &Spacing) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::Eq for Spacing {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
1059#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1060pub enum Spacing {
1061/// A `Punct` token can join with the following token to form a multi-character operator.
1062 ///
1063 /// In token streams constructed using proc macro interfaces, `Joint` punctuation tokens can be
1064 /// followed by any other tokens. However, in token streams parsed from source code, the
1065 /// compiler will only set spacing to `Joint` in the following cases.
1066 /// - When a `Punct` is immediately followed by another `Punct` without a whitespace. E.g. `+`
1067 /// is `Joint` in `+=` and `++`.
1068 /// - When a single quote `'` is immediately followed by an identifier without a whitespace.
1069 /// E.g. `'` is `Joint` in `'lifetime`.
1070 ///
1071 /// This list may be extended in the future to enable more token combinations.
1072#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1073Joint,
1074/// A `Punct` token cannot join with the following token to form a multi-character operator.
1075 ///
1076 /// `Alone` punctuation tokens can be followed by any other tokens. In token streams parsed
1077 /// from source code, the compiler will set spacing to `Alone` in all cases not covered by the
1078 /// conditions for `Joint` above. E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`. In
1079 /// particular, tokens not followed by anything will be marked as `Alone`.
1080#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1081Alone,
1082}
10831084impl Punct {
1085/// Creates a new `Punct` from the given character and spacing.
1086 /// The `ch` argument must be a valid punctuation character permitted by the language,
1087 /// otherwise the function will panic.
1088 ///
1089 /// The returned `Punct` will have the default span of `Span::call_site()`
1090 /// which can be further configured with the `set_span` method below.
1091#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1092pub fn new(ch: char, spacing: Spacing) -> Punct {
1093const LEGAL_CHARS: &[char] = &[
1094'=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
1095':', '#', '$', '?', '\'',
1096 ];
1097if !LEGAL_CHARS.contains(&ch) {
1098{
::core::panicking::panic_fmt(format_args!("unsupported character `{0:?}`",
ch));
};panic!("unsupported character `{:?}`", ch);
1099 }
1100Punct(bridge::Punct {
1101 ch: chas u8,
1102 joint: spacing == Spacing::Joint,
1103 span: Span::call_site().0,
1104 })
1105 }
11061107/// Returns the value of this punctuation character as `char`.
1108#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1109pub fn as_char(&self) -> char {
1110self.0.ch as char1111 }
11121113/// Returns the spacing of this punctuation character, indicating whether it can be potentially
1114 /// combined into a multi-character operator with the following token (`Joint`), or whether the
1115 /// operator has definitely ended (`Alone`).
1116#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1117pub fn spacing(&self) -> Spacing {
1118if self.0.joint { Spacing::Joint } else { Spacing::Alone }
1119 }
11201121/// Returns the span for this punctuation character.
1122#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1123pub fn span(&self) -> Span {
1124Span(self.0.span)
1125 }
11261127/// Configure the span for this punctuation character.
1128#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1129pub fn set_span(&mut self, span: Span) {
1130self.0.span = span.0;
1131 }
1132}
11331134/// Prints the punctuation character as a string that should be losslessly convertible
1135/// back into the same character.
1136#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1137impl fmt::Displayfor Punct {
1138fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1139f.write_fmt(format_args!("{0}", self.as_char()))write!(f, "{}", self.as_char())1140 }
1141}
11421143#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1144impl fmt::Debugfor Punct {
1145fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1146f.debug_struct("Punct")
1147 .field("ch", &self.as_char())
1148 .field("spacing", &self.spacing())
1149 .field("span", &self.span())
1150 .finish()
1151 }
1152}
11531154#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1155impl PartialEq<char> for Punct {
1156fn eq(&self, rhs: &char) -> bool {
1157self.as_char() == *rhs1158 }
1159}
11601161#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1162impl PartialEq<Punct> for char {
1163fn eq(&self, rhs: &Punct) -> bool {
1164*self == rhs.as_char()
1165 }
1166}
11671168/// An identifier (`ident`).
1169#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Ident {
#[inline]
fn clone(&self) -> Ident { Ident(::core::clone::Clone::clone(&self.0)) }
}Clone)]
1170#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1171pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
11721173impl Ident {
1174/// Creates a new `Ident` with the given `string` as well as the specified
1175 /// `span`.
1176 /// The `string` argument must be a valid identifier permitted by the
1177 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1178 ///
1179 /// The constructed identifier will be NFC-normalized. See the [Reference] for more info.
1180 ///
1181 /// Note that `span`, currently in rustc, configures the hygiene information
1182 /// for this identifier.
1183 ///
1184 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1185 /// meaning that identifiers created with this span will be resolved as if they were written
1186 /// directly at the location of the macro call, and other code at the macro call site will be
1187 /// able to refer to them as well.
1188 ///
1189 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1190 /// meaning that identifiers created with this span will be resolved at the location of the
1191 /// macro definition and other code at the macro call site will not be able to refer to them.
1192 ///
1193 /// Due to the current importance of hygiene this constructor, unlike other
1194 /// tokens, requires a `Span` to be specified at construction.
1195 ///
1196 /// [Reference]: https://doc.rust-lang.org/nightly/reference/identifiers.html#r-ident.normalization
1197#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1198pub fn new(string: &str, span: Span) -> Ident {
1199Ident(bridge::Ident {
1200 sym: bridge::client::Symbol::new_ident(string, false),
1201 is_raw: false,
1202 span: span.0,
1203 })
1204 }
12051206/// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1207 /// The `string` argument be a valid identifier permitted by the language
1208 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1209 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1210#[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1211pub fn new_raw(string: &str, span: Span) -> Ident {
1212Ident(bridge::Ident {
1213 sym: bridge::client::Symbol::new_ident(string, true),
1214 is_raw: true,
1215 span: span.0,
1216 })
1217 }
12181219/// Returns the span of this `Ident`, encompassing the entire string returned
1220 /// by [`to_string`](ToString::to_string).
1221#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1222pub fn span(&self) -> Span {
1223Span(self.0.span)
1224 }
12251226/// Configures the span of this `Ident`, possibly changing its hygiene context.
1227#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1228pub fn set_span(&mut self, span: Span) {
1229self.0.span = span.0;
1230 }
1231}
12321233/// Prints the identifier as a string that should be losslessly convertible back
1234/// into the same identifier.
1235#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1236impl fmt::Displayfor Ident {
1237fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1238if self.0.is_raw {
1239 f.write_str("r#")?;
1240 }
1241 fmt::Display::fmt(&self.0.sym, f)
1242 }
1243}
12441245#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1246impl fmt::Debugfor Ident {
1247fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1248f.debug_struct("Ident")
1249 .field("ident", &self.to_string())
1250 .field("span", &self.span())
1251 .finish()
1252 }
1253}
12541255/// A literal string (`"hello"`), byte string (`b"hello"`), C string (`c"hello"`),
1256/// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1257/// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1258/// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1259#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Literal {
#[inline]
fn clone(&self) -> Literal {
Literal(::core::clone::Clone::clone(&self.0))
}
}Clone)]
1260#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1261pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
12621263macro_rules!suffixed_int_literals {
1264 ($($name:ident => $kind:ident,)*) => ($(
1265/// Creates a new suffixed integer literal with the specified value.
1266 ///
1267 /// This function will create an integer like `1u32` where the integer
1268 /// value specified is the first part of the token and the integral is
1269 /// also suffixed at the end.
1270 /// Literals created from negative numbers might not survive round-trips through
1271 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1272 ///
1273 /// Literals created through this method have the `Span::call_site()`
1274 /// span by default, which can be configured with the `set_span` method
1275 /// below.
1276#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1277pub fn $name(n: $kind) -> Literal {
1278 Literal(bridge::Literal {
1279 kind: bridge::LitKind::Integer,
1280 symbol: bridge::client::Symbol::new(&n.to_string()),
1281 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1282 span: Span::call_site().0,
1283 })
1284 }
1285 )*)
1286}
12871288macro_rules!unsuffixed_int_literals {
1289 ($($name:ident => $kind:ident,)*) => ($(
1290/// Creates a new unsuffixed integer literal with the specified value.
1291 ///
1292 /// This function will create an integer like `1` where the integer
1293 /// value specified is the first part of the token. No suffix is
1294 /// specified on this token, meaning that invocations like
1295 /// `Literal::i8_unsuffixed(1)` are equivalent to
1296 /// `Literal::u32_unsuffixed(1)`.
1297 /// Literals created from negative numbers might not survive roundtrips through
1298 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1299 ///
1300 /// Literals created through this method have the `Span::call_site()`
1301 /// span by default, which can be configured with the `set_span` method
1302 /// below.
1303#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1304pub fn $name(n: $kind) -> Literal {
1305 Literal(bridge::Literal {
1306 kind: bridge::LitKind::Integer,
1307 symbol: bridge::client::Symbol::new(&n.to_string()),
1308 suffix: None,
1309 span: Span::call_site().0,
1310 })
1311 }
1312 )*)
1313}
13141315macro_rules!integer_values {
1316 ($($nb:ident => $fn_name:ident,)+) => {
1317 $(
1318#[doc = concat!(
1319"Returns the unescaped `",
1320stringify!($nb),
1321"` value if the literal is a `",
1322stringify!($nb),
1323"` or if it's an \"unmarked\" integer which doesn't overflow.")]
1324 #[unstable(feature = "proc_macro_value", issue = "136652")]
1325pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1326if self.0.kind != bridge::LitKind::Integer {
1327return Err(ConversionErrorKind::InvalidLiteralKind);
1328 }
1329self.with_symbol_and_suffix(|symbol, suffix| {
1330match suffix {
1331stringify!($nb) | "" => {
1332let symbol = strip_underscores(symbol);
1333let (number, base) = parse_number(&symbol);
1334$nb::from_str_radix(&number, base as u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1335 }
1336_ => Err(ConversionErrorKind::InvalidLiteralKind),
1337 }
1338 })
1339 }
1340 )+
1341 }
1342}
13431344macro_rules!float_values {
1345 ($($nb:ident => $fn_name:ident,)+) => {
1346 $(
1347#[doc = concat!(
1348"Returns the unescaped `",
1349stringify!($nb),
1350"` value if the literal is a `",
1351stringify!($nb),
1352"` or if it's an \"unmarked\" float which doesn't overflow.")]
1353 #[unstable(feature = "proc_macro_value", issue = "136652")]
1354pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1355if self.0.kind != bridge::LitKind::Float {
1356return Err(ConversionErrorKind::InvalidLiteralKind);
1357 }
1358self.with_symbol_and_suffix(|symbol, suffix| {
1359match suffix {
1360stringify!($nb) | "" => {
1361let number = strip_underscores(symbol);
1362$nb::from_str(&number).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1363 }
1364_ => Err(ConversionErrorKind::InvalidLiteralKind),
1365 }
1366 })
1367 }
1368 )+
1369 }
1370}
13711372impl Literal {
1373fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1374Literal(bridge::Literal {
1375kind,
1376 symbol: bridge::client::Symbol::new(value),
1377 suffix: suffix.map(bridge::client::Symbol::new),
1378 span: Span::call_site().0,
1379 })
1380 }
13811382/// 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! {
1383 u8_suffixed => u8,
1384 u16_suffixed => u16,
1385 u32_suffixed => u32,
1386 u64_suffixed => u64,
1387 u128_suffixed => u128,
1388 usize_suffixed => usize,
1389 i8_suffixed => i8,
1390 i16_suffixed => i16,
1391 i32_suffixed => i32,
1392 i64_suffixed => i64,
1393 i128_suffixed => i128,
1394 isize_suffixed => isize,
1395 }13961397/// 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! {
1398 u8_unsuffixed => u8,
1399 u16_unsuffixed => u16,
1400 u32_unsuffixed => u32,
1401 u64_unsuffixed => u64,
1402 u128_unsuffixed => u128,
1403 usize_unsuffixed => usize,
1404 i8_unsuffixed => i8,
1405 i16_unsuffixed => i16,
1406 i32_unsuffixed => i32,
1407 i64_unsuffixed => i64,
1408 i128_unsuffixed => i128,
1409 isize_unsuffixed => isize,
1410 }14111412/// Creates a new unsuffixed floating-point literal.
1413 ///
1414 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1415 /// the float's value is emitted directly into the token but no suffix is
1416 /// used, so it may be inferred to be a `f64` later in the compiler.
1417 /// Literals created from negative numbers might not survive roundtrips through
1418 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1419 ///
1420 /// # Panics
1421 ///
1422 /// This function requires that the specified float is finite, for
1423 /// example if it is infinity or NaN this function will panic.
1424#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1425pub fn f32_unsuffixed(n: f32) -> Literal {
1426if !n.is_finite() {
1427{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1428 }
1429let mut repr = n.to_string();
1430if !repr.contains('.') {
1431repr.push_str(".0");
1432 }
1433Literal::new(bridge::LitKind::Float, &repr, None)
1434 }
14351436/// Creates a new suffixed floating-point literal.
1437 ///
1438 /// This constructor will create a literal like `1.0f32` where the value
1439 /// specified is the preceding part of the token and `f32` is the suffix of
1440 /// the token. This token will always be inferred to be an `f32` in the
1441 /// compiler.
1442 /// Literals created from negative numbers might not survive roundtrips through
1443 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1444 ///
1445 /// # Panics
1446 ///
1447 /// This function requires that the specified float is finite, for
1448 /// example if it is infinity or NaN this function will panic.
1449#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1450pub fn f32_suffixed(n: f32) -> Literal {
1451if !n.is_finite() {
1452{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1453 }
1454Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1455 }
14561457/// Creates a new unsuffixed floating-point literal.
1458 ///
1459 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1460 /// the float's value is emitted directly into the token but no suffix is
1461 /// used, so it may be inferred to be a `f64` later in the compiler.
1462 /// Literals created from negative numbers might not survive roundtrips through
1463 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1464 ///
1465 /// # Panics
1466 ///
1467 /// This function requires that the specified float is finite, for
1468 /// example if it is infinity or NaN this function will panic.
1469#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1470pub fn f64_unsuffixed(n: f64) -> Literal {
1471if !n.is_finite() {
1472{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1473 }
1474let mut repr = n.to_string();
1475if !repr.contains('.') {
1476repr.push_str(".0");
1477 }
1478Literal::new(bridge::LitKind::Float, &repr, None)
1479 }
14801481/// Creates a new suffixed floating-point literal.
1482 ///
1483 /// This constructor will create a literal like `1.0f64` where the value
1484 /// specified is the preceding part of the token and `f64` is the suffix of
1485 /// the token. This token will always be inferred to be an `f64` in the
1486 /// compiler.
1487 /// Literals created from negative numbers might not survive roundtrips through
1488 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1489 ///
1490 /// # Panics
1491 ///
1492 /// This function requires that the specified float is finite, for
1493 /// example if it is infinity or NaN this function will panic.
1494#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1495pub fn f64_suffixed(n: f64) -> Literal {
1496if !n.is_finite() {
1497{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1498 }
1499Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1500 }
15011502/// String literal.
1503#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1504pub fn string(string: &str) -> Literal {
1505let escape = EscapeOptions {
1506 escape_single_quote: false,
1507 escape_double_quote: true,
1508 escape_nonascii: false,
1509 };
1510let repr = escape_bytes(string.as_bytes(), escape);
1511Literal::new(bridge::LitKind::Str, &repr, None)
1512 }
15131514/// Character literal.
1515#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1516pub fn character(ch: char) -> Literal {
1517let escape = EscapeOptions {
1518 escape_single_quote: true,
1519 escape_double_quote: false,
1520 escape_nonascii: false,
1521 };
1522let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1523Literal::new(bridge::LitKind::Char, &repr, None)
1524 }
15251526/// Byte character literal.
1527#[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1528pub fn byte_character(byte: u8) -> Literal {
1529let escape = EscapeOptions {
1530 escape_single_quote: true,
1531 escape_double_quote: false,
1532 escape_nonascii: true,
1533 };
1534let repr = escape_bytes(&[byte], escape);
1535Literal::new(bridge::LitKind::Byte, &repr, None)
1536 }
15371538/// Byte string literal.
1539#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1540pub fn byte_string(bytes: &[u8]) -> Literal {
1541let escape = EscapeOptions {
1542 escape_single_quote: false,
1543 escape_double_quote: true,
1544 escape_nonascii: true,
1545 };
1546let repr = escape_bytes(bytes, escape);
1547Literal::new(bridge::LitKind::ByteStr, &repr, None)
1548 }
15491550/// C string literal.
1551#[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1552pub fn c_string(string: &CStr) -> Literal {
1553let escape = EscapeOptions {
1554 escape_single_quote: false,
1555 escape_double_quote: true,
1556 escape_nonascii: false,
1557 };
1558let repr = escape_bytes(string.to_bytes(), escape);
1559Literal::new(bridge::LitKind::CStr, &repr, None)
1560 }
15611562/// Returns the span encompassing this literal.
1563#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1564pub fn span(&self) -> Span {
1565Span(self.0.span)
1566 }
15671568/// Configures the span associated for this literal.
1569#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1570pub fn set_span(&mut self, span: Span) {
1571self.0.span = span.0;
1572 }
15731574/// Returns a `Span` that is a subset of `self.span()` containing only the
1575 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1576 /// span is outside the bounds of `self`.
1577// FIXME(SergioBenitez): check that the byte range starts and ends at a
1578 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1579 // occur elsewhere when the source text is printed.
1580 // FIXME(SergioBenitez): there is no way for the user to know what
1581 // `self.span()` actually maps to, so this method can currently only be
1582 // called blindly. For example, `to_string()` for the character 'c' returns
1583 // "'\u{63}'"; there is no way for the user to know whether the source text
1584 // was 'c' or whether it was '\u{63}'.
1585#[unstable(feature = "proc_macro_span", issue = "54725")]
1586pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1587BridgeMethods::span_subspan(
1588self.0.span,
1589range.start_bound().cloned(),
1590range.end_bound().cloned(),
1591 )
1592 .map(Span)
1593 }
15941595fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1596self.0.symbol.with(|symbol| match self.0.suffix {
1597Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1598None => f(symbol, ""),
1599 })
1600 }
16011602/// Invokes the callback with a `&[&str]` consisting of each part of the
1603 /// literal's representation. This is done to allow the `ToString` and
1604 /// `Display` implementations to borrow references to symbol values, and
1605 /// both be optimized to reduce overhead.
1606fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1607/// Returns a string containing exactly `num` '#' characters.
1608 /// Uses a 256-character source string literal which is always safe to
1609 /// index with a `u8` index.
1610fn get_hashes_str(num: u8) -> &'static str {
1611const HASHES: &str = "\
1612 ################################################################\
1613 ################################################################\
1614 ################################################################\
1615 ################################################################\
1616 ";
1617const _: () = if !(HASHES.len() == 256) {
::core::panicking::panic("assertion failed: HASHES.len() == 256")
}assert!(HASHES.len() == 256);
1618&HASHES[..num as usize]
1619 }
16201621self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1622 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1623 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1624 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1625 bridge::LitKind::StrRaw(n) => {
1626let hashes = get_hashes_str(n);
1627f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1628 }
1629 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1630 bridge::LitKind::ByteStrRaw(n) => {
1631let hashes = get_hashes_str(n);
1632f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1633 }
1634 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1635 bridge::LitKind::CStrRaw(n) => {
1636let hashes = get_hashes_str(n);
1637f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1638 }
16391640 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1641f(&[symbol, suffix])
1642 }
1643 })
1644 }
16451646/// Returns the unescaped character value if the current literal is a byte character literal.
1647#[unstable(feature = "proc_macro_value", issue = "136652")]
1648pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1649self.0.symbol.with(|symbol| match self.0.kind {
1650 bridge::LitKind::Byte => unescape_byte(symbol)
1651 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1652_ => Err(ConversionErrorKind::InvalidLiteralKind),
1653 })
1654 }
16551656/// Returns the unescaped character value if the current literal is a character literal.
1657#[unstable(feature = "proc_macro_value", issue = "136652")]
1658pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1659self.0.symbol.with(|symbol| match self.0.kind {
1660 bridge::LitKind::Char => unescape_char(symbol)
1661 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1662_ => Err(ConversionErrorKind::InvalidLiteralKind),
1663 })
1664 }
16651666/// Returns the unescaped string value if the current literal is a string or a string literal.
1667#[unstable(feature = "proc_macro_value", issue = "136652")]
1668pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1669self.0.symbol.with(|symbol| match self.0.kind {
1670 bridge::LitKind::Str => {
1671if symbol.contains('\\') {
1672let mut buf = String::with_capacity(symbol.len());
1673let mut error = None;
1674// Force-inlining here is aggressive but the closure is
1675 // called on every char in the string, so it can be hot in
1676 // programs with many long strings containing escapes.
1677unescape_str(
1678symbol,
1679#[inline(always)]
1680|_, c| match c {
1681Ok(c) => buf.push(c),
1682Err(err) => {
1683if err.is_fatal() {
1684error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1685 }
1686 }
1687 },
1688 );
1689if let Some(error) = error { Err(error) } else { Ok(buf) }
1690 } else {
1691Ok(symbol.to_string())
1692 }
1693 }
1694 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1695_ => Err(ConversionErrorKind::InvalidLiteralKind),
1696 })
1697 }
16981699/// Returns the unescaped string value if the current literal is a c-string or a c-string
1700 /// literal.
1701#[unstable(feature = "proc_macro_value", issue = "136652")]
1702pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1703self.0.symbol.with(|symbol| match self.0.kind {
1704 bridge::LitKind::CStr => {
1705let mut error = None;
1706let mut buf = Vec::with_capacity(symbol.len());
17071708unescape_c_str(symbol, |_span, res| match res {
1709Ok(MixedUnit::Char(c)) => {
1710buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1711 }
1712Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1713Err(err) => {
1714if err.is_fatal() {
1715error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1716 }
1717 }
1718 });
1719if let Some(error) = error {
1720Err(error)
1721 } else {
1722buf.push(0);
1723Ok(buf)
1724 }
1725 }
1726 bridge::LitKind::CStrRaw(_) => {
1727// Raw strings have no escapes so we can convert the symbol
1728 // directly to a `Lrc<u8>` after appending the terminating NUL
1729 // char.
1730let mut buf = symbol.to_owned().into_bytes();
1731buf.push(0);
1732Ok(buf)
1733 }
1734_ => Err(ConversionErrorKind::InvalidLiteralKind),
1735 })
1736 }
17371738/// Returns the unescaped string value if the current literal is a byte string or a byte string
1739 /// literal.
1740#[unstable(feature = "proc_macro_value", issue = "136652")]
1741pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1742self.0.symbol.with(|symbol| match self.0.kind {
1743 bridge::LitKind::ByteStr => {
1744let mut buf = Vec::with_capacity(symbol.len());
1745let mut error = None;
17461747unescape_byte_str(symbol, |_, res| match res {
1748Ok(b) => buf.push(b),
1749Err(err) => {
1750if err.is_fatal() {
1751error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1752 }
1753 }
1754 });
1755if let Some(error) = error { Err(error) } else { Ok(buf) }
1756 }
1757 bridge::LitKind::ByteStrRaw(_) => {
1758// Raw strings have no escapes so we can convert the symbol
1759 // directly to a `Lrc<u8>`.
1760Ok(symbol.to_owned().into_bytes())
1761 }
1762_ => Err(ConversionErrorKind::InvalidLiteralKind),
1763 })
1764 }
17651766#[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! {
1767 u8 => u8_value,
1768 u16 => u16_value,
1769 u32 => u32_value,
1770 u64 => u64_value,
1771 u128 => u128_value,
1772 i8 => i8_value,
1773 i16 => i16_value,
1774 i32 => i32_value,
1775 i64 => i64_value,
1776 i128 => i128_value,
1777 }17781779#[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! {
1780 f16 => f16_value,
1781 f32 => f32_value,
1782 f64 => f64_value,
1783// FIXME: `f128` doesn't implement `FromStr` for the moment so we cannot obtain it from
1784 // a `&str`. To be uncommented when it's added.
1785 // f128 => f128_value,
1786}1787}
17881789#[repr(u32)]
1790#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for Base {
#[inline]
fn eq(&self, other: &Base) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Base {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
1791enum Base {
1792 Decimal = 10,
1793 Binary = 2,
1794 Octal = 8,
1795 Hexadecimal = 16,
1796}
17971798fn parse_number(value: &str) -> (&str, Base) {
1799let mut iter = value.as_bytes().iter().copied();
1800let Some(first_digit) = iter.next() else {
1801return ("0", Base::Decimal);
1802 };
1803let Some(second_digit) = iter.next() else {
1804return (value, Base::Decimal);
1805 };
18061807let mut base = Base::Decimal;
1808if first_digit == b'0' {
1809// Attempt to parse encoding base.
1810match second_digit {
1811b'b' => {
1812base = Base::Binary;
1813 }
1814b'o' => {
1815base = Base::Octal;
1816 }
1817b'x' => {
1818base = Base::Hexadecimal;
1819 }
1820_ => {}
1821 }
1822 }
18231824let offset = if base == Base::Decimal { 0 } else { 2 };
18251826 (&value[offset..], base)
1827}
18281829fn strip_underscores(value_s: &str) -> Cow<'_, str> {
1830let value = value_s.as_bytes();
1831if value.iter().copied().all(|c| c != b'_' && c != b'f') {
1832return Cow::Borrowed(value_s);
1833 }
1834let mut output = String::with_capacity(value.len());
1835for c in value.iter().copied() {
1836if c != b'_' {
1837 output.push(c as char);
1838 }
1839 }
1840 Cow::Owned(output)
1841}
18421843/// Parse a single literal from its stringified representation.
1844///
1845/// In order to parse successfully, the input string must not contain anything
1846/// but the literal token. Specifically, it must not contain whitespace or
1847/// comments in addition to the literal.
1848///
1849/// The resulting literal token will have a `Span::call_site()` span.
1850///
1851/// NOTE: some errors may cause panics instead of returning `LexError`. We
1852/// reserve the right to change these errors into `LexError`s later.
1853#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1854impl FromStrfor Literal {
1855type Err = LexError;
18561857fn from_str(src: &str) -> Result<Self, LexError> {
1858match BridgeMethods::literal_from_str(src) {
1859Ok(literal) => Ok(Literal(literal)),
1860Err(msg) => Err(LexError(msg)),
1861 }
1862 }
1863}
18641865/// Prints the literal as a string that should be losslessly convertible
1866/// back into the same literal (except for possible rounding for floating point literals).
1867#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1868impl fmt::Displayfor Literal {
1869fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1870self.with_stringify_parts(|parts| {
1871for part in parts {
1872 fmt::Display::fmt(part, f)?;
1873 }
1874Ok(())
1875 })
1876 }
1877}
18781879#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1880impl fmt::Debugfor Literal {
1881fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1882f.debug_struct("Literal")
1883// format the kind on one line even in {:#?} mode
1884 .field("kind", &format_args!("{0:?}", self.0.kind)format_args!("{:?}", self.0.kind))
1885 .field("symbol", &self.0.symbol)
1886// format `Some("...")` on one line even in {:#?} mode
1887 .field("suffix", &format_args!("{0:?}", self.0.suffix)format_args!("{:?}", self.0.suffix))
1888 .field("span", &self.0.span)
1889 .finish()
1890 }
1891}
18921893#[unstable(
1894 feature = "proc_macro_tracked_path",
1895 issue = "99515",
1896 implied_by = "proc_macro_tracked_env"
1897)]
1898/// Functionality for adding environment state to the build dependency info.
1899pub mod tracked {
1900use std::env::{self, VarError};
1901use std::ffi::OsStr;
1902use std::path::Path;
19031904use crate::BridgeMethods;
19051906/// Retrieve an environment variable and add it to build dependency info.
1907 /// The build system executing the compiler will know that the variable was accessed during
1908 /// compilation, and will be able to rerun the build when the value of that variable changes.
1909 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1910 /// standard library, except that the argument must be UTF-8.
1911#[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1912pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1913let key: &str = key.as_ref();
1914let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1915BridgeMethods::track_env_var(key, value.as_deref().ok());
1916value1917 }
19181919/// Track a file or directory explicitly.
1920 ///
1921 /// Commonly used for tracking asset preprocessing.
1922#[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1923pub fn path<P: AsRef<Path>>(path: P) {
1924let path: &str = path.as_ref().to_str().unwrap();
1925BridgeMethods::track_path(path);
1926 }
1927}