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 {
static __NAMES: &str =
"ZeroCharsMoreThanOneCharLoneSlashInvalidEscapeBareCarriageReturnBareCarriageReturnInRawStringEscapeOnlyCharTooShortHexEscapeInvalidCharInHexEscapeOutOfRangeHexEscapeNoBraceInUnicodeEscapeInvalidCharInUnicodeEscapeEmptyUnicodeEscapeUnclosedUnicodeEscapeLeadingUnderscoreUnicodeEscapeOverlongUnicodeEscapeLoneSurrogateUnicodeEscapeOutOfRangeUnicodeEscapeUnicodeEscapeInByteNonAsciiCharInByteNulInCStrUnskippedWhitespaceWarningMultipleSkippedLinesWarning";
static __OFFSET: [usize; 24] =
[0usize, 9usize, 24usize, 33usize, 46usize, 64usize, 93usize,
107usize, 124usize, 146usize, 165usize, 187usize, 213usize,
231usize, 252usize, 282usize, 303usize, 329usize, 352usize,
371usize, 389usize, 398usize, 424usize, 451usize];
let __d = ::core::intrinsics::discriminant_value(self) as usize;
::core::fmt::Formatter::debug_c_like_enum_write_str(f, __NAMES,
&__OFFSET, __d)
}
}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#[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)]
249pub struct LexError(String);
250251#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
252impl fmt::Displayfor LexError {
253fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254f.write_str(&self.0)
255 }
256}
257258#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
259impl error::Errorfor LexError {}
260261#[stable(feature = "proc_macro_lib", since = "1.15.0")]
262impl !Sendfor LexError {}
263#[stable(feature = "proc_macro_lib", since = "1.15.0")]
264impl !Syncfor LexError {}
265266/// Error returned from `TokenStream::expand_expr`.
267#[unstable(feature = "proc_macro_expand", issue = "90765")]
268#[non_exhaustive]
269#[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)]
270pub struct ExpandError;
271272#[unstable(feature = "proc_macro_expand", issue = "90765")]
273impl fmt::Displayfor ExpandError {
274fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275f.write_str("macro expansion failed")
276 }
277}
278279#[unstable(feature = "proc_macro_expand", issue = "90765")]
280impl error::Errorfor ExpandError {}
281282#[unstable(feature = "proc_macro_expand", issue = "90765")]
283impl !Sendfor ExpandError {}
284285#[unstable(feature = "proc_macro_expand", issue = "90765")]
286impl !Syncfor ExpandError {}
287288impl TokenStream {
289/// Returns an empty `TokenStream` containing no token trees.
290#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
291pub fn new() -> TokenStream {
292TokenStream(None)
293 }
294295/// Checks if this `TokenStream` is empty.
296#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
297pub fn is_empty(&self) -> bool {
298self.0.as_ref().map(BridgeMethods::ts_is_empty).unwrap_or(true)
299 }
300301/// Parses this `TokenStream` as an expression and attempts to expand any
302 /// macros within it. Returns the expanded `TokenStream`.
303 ///
304 /// Currently only expressions expanding to literals will succeed, although
305 /// this may be relaxed in the future.
306 ///
307 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
308 /// report an error, failing compilation, and/or return an `Err(..)`. The
309 /// specific behavior for any error condition, and what conditions are
310 /// considered errors, is unspecified and may change in the future.
311#[unstable(feature = "proc_macro_expand", issue = "90765")]
312pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
313let stream = self.0.as_ref().ok_or(ExpandError)?;
314match BridgeMethods::ts_expand_expr(stream) {
315Ok(stream) => Ok(TokenStream(Some(stream))),
316Err(_) => Err(ExpandError),
317 }
318 }
319}
320321/// Attempts to break the string into tokens and parse those tokens into a token stream.
322/// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
323/// or characters not existing in the language.
324/// All tokens in the parsed stream get `Span::call_site()` spans.
325///
326/// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
327/// change these errors into `LexError`s later.
328#[stable(feature = "proc_macro_lib", since = "1.15.0")]
329impl FromStrfor TokenStream {
330type Err = LexError;
331332fn from_str(src: &str) -> Result<TokenStream, LexError> {
333Ok(TokenStream(Some(BridgeMethods::ts_from_str(src).map_err(LexError)?)))
334 }
335}
336337/// Prints the token stream as a string that is supposed to be losslessly convertible back
338/// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
339/// with `Delimiter::None` delimiters and negative numeric literals.
340///
341/// Note: the exact form of the output is subject to change, e.g. there might
342/// be changes in the whitespace used between tokens. Therefore, you should
343/// *not* do any kind of simple substring matching on the output string (as
344/// produced by `to_string`) to implement a proc macro, because that matching
345/// might stop working if such changes happen. Instead, you should work at the
346/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
347/// `TokenTree::Punct`, or `TokenTree::Literal`.
348#[stable(feature = "proc_macro_lib", since = "1.15.0")]
349impl fmt::Displayfor TokenStream {
350fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351match &self.0 {
352Some(ts) => f.write_fmt(format_args!("{0}", BridgeMethods::ts_to_string(ts)))write!(f, "{}", BridgeMethods::ts_to_string(ts)),
353None => Ok(()),
354 }
355 }
356}
357358/// Prints tokens in a form convenient for debugging.
359#[stable(feature = "proc_macro_lib", since = "1.15.0")]
360impl fmt::Debugfor TokenStream {
361fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362 f.write_str("TokenStream ")?;
363f.debug_list().entries(self.clone()).finish()
364 }
365}
366367#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
368impl Defaultfor TokenStream {
369fn default() -> Self {
370TokenStream::new()
371 }
372}
373374#[unstable(feature = "proc_macro_quote", issue = "54722")]
375pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
376377fn tree_to_bridge_tree(
378 tree: TokenTree,
379) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
380match tree {
381 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
382 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
383 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
384 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
385 }
386}
387388/// Creates a token stream containing a single token tree.
389#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
390impl From<TokenTree> for TokenStream {
391fn from(tree: TokenTree) -> TokenStream {
392TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
393 }
394}
395396/// Non-generic helper for implementing `FromIterator<TokenTree>` and
397/// `Extend<TokenTree>` with less monomorphization in calling crates.
398struct ConcatTreesHelper {
399 trees: Vec<
400 bridge::TokenTree<
401 bridge::client::TokenStream,
402 bridge::client::Span,
403 bridge::client::Symbol,
404 >,
405 >,
406}
407408impl ConcatTreesHelper {
409fn new(capacity: usize) -> Self {
410ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
411 }
412413fn push(&mut self, tree: TokenTree) {
414self.trees.push(tree_to_bridge_tree(tree));
415 }
416417fn build(self) -> TokenStream {
418if self.trees.is_empty() {
419TokenStream(None)
420 } else {
421TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
422 }
423 }
424425fn append_to(self, stream: &mut TokenStream) {
426if self.trees.is_empty() {
427return;
428 }
429stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
430 }
431}
432433/// Non-generic helper for implementing `FromIterator<TokenStream>` and
434/// `Extend<TokenStream>` with less monomorphization in calling crates.
435struct ConcatStreamsHelper {
436 streams: Vec<bridge::client::TokenStream>,
437}
438439impl ConcatStreamsHelper {
440fn new(capacity: usize) -> Self {
441ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
442 }
443444fn push(&mut self, stream: TokenStream) {
445if let Some(stream) = stream.0 {
446self.streams.push(stream);
447 }
448 }
449450fn build(mut self) -> TokenStream {
451if self.streams.len() <= 1 {
452TokenStream(self.streams.pop())
453 } else {
454TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
455 }
456 }
457458fn append_to(mut self, stream: &mut TokenStream) {
459if self.streams.is_empty() {
460return;
461 }
462let base = stream.0.take();
463if base.is_none() && self.streams.len() == 1 {
464stream.0 = self.streams.pop();
465 } else {
466stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
467 }
468 }
469}
470471/// Collects a number of token trees into a single stream.
472#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
473impl FromIterator<TokenTree> for TokenStream {
474fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
475let iter = trees.into_iter();
476let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
477iter.for_each(|tree| builder.push(tree));
478builder.build()
479 }
480}
481482/// A "flattening" operation on token streams, collects token trees
483/// from multiple token streams into a single stream.
484#[stable(feature = "proc_macro_lib", since = "1.15.0")]
485impl FromIterator<TokenStream> for TokenStream {
486fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
487let iter = streams.into_iter();
488let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
489iter.for_each(|stream| builder.push(stream));
490builder.build()
491 }
492}
493494#[stable(feature = "token_stream_extend", since = "1.30.0")]
495impl Extend<TokenTree> for TokenStream {
496fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
497let iter = trees.into_iter();
498let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
499iter.for_each(|tree| builder.push(tree));
500builder.append_to(self);
501 }
502}
503504#[stable(feature = "token_stream_extend", since = "1.30.0")]
505impl Extend<TokenStream> for TokenStream {
506fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
507let iter = streams.into_iter();
508let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
509iter.for_each(|stream| builder.push(stream));
510builder.append_to(self);
511 }
512}
513514macro_rules!extend_items {
515 ($($item:ident)*) => {
516 $(
517#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
518impl Extend<$item> for TokenStream {
519fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
520self.extend(iter.into_iter().map(TokenTree::$item));
521 }
522 }
523 )*
524 };
525}
526527#[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);
528529/// Public implementation details for the `TokenStream` type, such as iterators.
530#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
531pub mod token_stream {
532use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
533534/// An iterator over `TokenStream`'s `TokenTree`s.
535 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
536 /// and returns whole groups as token trees.
537#[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)]
538 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
539pub struct IntoIter(
540 std::vec::IntoIter<
541 bridge::TokenTree<
542 bridge::client::TokenStream,
543 bridge::client::Span,
544 bridge::client::Symbol,
545 >,
546 >,
547 );
548549#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
550impl Iteratorfor IntoIter {
551type Item = TokenTree;
552553fn next(&mut self) -> Option<TokenTree> {
554self.0.next().map(|tree| match tree {
555 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
556 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
557 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
558 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
559 })
560 }
561562fn size_hint(&self) -> (usize, Option<usize>) {
563self.0.size_hint()
564 }
565566fn count(self) -> usize {
567self.0.count()
568 }
569 }
570571#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
572impl IntoIteratorfor TokenStream {
573type Item = TokenTree;
574type IntoIter = IntoIter;
575576fn into_iter(self) -> IntoIter {
577IntoIter(self.0.map(BridgeMethods::ts_into_trees).unwrap_or_default().into_iter())
578 }
579 }
580}
581582/// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
583/// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
584/// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
585///
586/// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
587/// To quote `$` itself, use `$$`.
588#[unstable(feature = "proc_macro_quote", issue = "54722")]
589#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
590#[rustc_builtin_macro]
591pub macro quote($($t:tt)*) {
592/* compiler built-in */
593}
594595#[unstable(feature = "proc_macro_internals", issue = "none")]
596#[doc(hidden)]
597mod quote;
598599/// A region of source code, along with macro expansion information.
600#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
601#[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)]
602pub struct Span(bridge::client::Span);
603604#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
605impl !Sendfor Span {}
606#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
607impl !Syncfor Span {}
608609macro_rules!diagnostic_method {
610 ($name:ident, $level:expr) => {
611/// Creates a new `Diagnostic` with the given `message` at the span
612 /// `self`.
613#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
614pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
615 Diagnostic::spanned(self, $level, message)
616 }
617 };
618}
619620impl Span {
621/// A span that resolves at the macro definition site.
622#[unstable(feature = "proc_macro_def_site", issue = "54724")]
623pub fn def_site() -> Span {
624Span(bridge::client::Span::def_site())
625 }
626627/// The span of the invocation of the current procedural macro.
628 /// Identifiers created with this span will be resolved as if they were written
629 /// directly at the macro call location (call-site hygiene) and other code
630 /// at the macro call site will be able to refer to them as well.
631#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
632pub fn call_site() -> Span {
633Span(bridge::client::Span::call_site())
634 }
635636/// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
637 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
638 /// call site (everything else).
639 /// The span location is taken from the call-site.
640#[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
641pub fn mixed_site() -> Span {
642Span(bridge::client::Span::mixed_site())
643 }
644645/// The `Span` for the tokens in the previous macro expansion from which
646 /// `self` was generated from, if any.
647#[unstable(feature = "proc_macro_span", issue = "54725")]
648pub fn parent(&self) -> Option<Span> {
649BridgeMethods::span_parent(self.0).map(Span)
650 }
651652/// The span for the origin source code that `self` was generated from. If
653 /// this `Span` wasn't generated from other macro expansions then the return
654 /// value is the same as `*self`.
655#[unstable(feature = "proc_macro_span", issue = "54725")]
656pub fn source(&self) -> Span {
657Span(BridgeMethods::span_source(self.0))
658 }
659660/// Returns the span's byte position range in the source file.
661#[unstable(feature = "proc_macro_span", issue = "54725")]
662pub fn byte_range(&self) -> Range<usize> {
663BridgeMethods::span_byte_range(self.0)
664 }
665666/// Creates an empty span pointing to directly before this span.
667#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
668pub fn start(&self) -> Span {
669Span(BridgeMethods::span_start(self.0))
670 }
671672/// Creates an empty span pointing to directly after this span.
673#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
674pub fn end(&self) -> Span {
675Span(BridgeMethods::span_end(self.0))
676 }
677678/// The one-indexed line of the source file where the span starts.
679 ///
680 /// To obtain the line of the span's end, use `span.end().line()`.
681#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
682pub fn line(&self) -> usize {
683BridgeMethods::span_line(self.0)
684 }
685686/// The one-indexed column of the source file where the span starts.
687 ///
688 /// To obtain the column of the span's end, use `span.end().column()`.
689#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
690pub fn column(&self) -> usize {
691BridgeMethods::span_column(self.0)
692 }
693694/// The path to the source file in which this span occurs, for display purposes.
695 ///
696 /// This might not correspond to a valid file system path.
697 /// It might be remapped (e.g. `"/src/lib.rs"`) or an artificial path (e.g. `"<command line>"`).
698#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
699pub fn file(&self) -> String {
700BridgeMethods::span_file(self.0)
701 }
702703/// The path to the source file in which this span occurs on the local file system.
704 ///
705 /// This is the actual path on disk. It is unaffected by path remapping.
706 ///
707 /// This path should not be embedded in the output of the macro; prefer `file()` instead.
708#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
709pub fn local_file(&self) -> Option<PathBuf> {
710BridgeMethods::span_local_file(self.0).map(PathBuf::from)
711 }
712713/// Creates a new span encompassing `self` and `other`.
714 ///
715 /// Returns `None` if `self` and `other` are from different files.
716#[unstable(feature = "proc_macro_span", issue = "54725")]
717pub fn join(&self, other: Span) -> Option<Span> {
718BridgeMethods::span_join(self.0, other.0).map(Span)
719 }
720721/// Creates a new span with the same line/column information as `self` but
722 /// that resolves symbols as though it were at `other`.
723#[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
724pub fn resolved_at(&self, other: Span) -> Span {
725Span(BridgeMethods::span_resolved_at(self.0, other.0))
726 }
727728/// Creates a new span with the same name resolution behavior as `self` but
729 /// with the line/column information of `other`.
730#[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
731pub fn located_at(&self, other: Span) -> Span {
732other.resolved_at(*self)
733 }
734735/// Compares two spans to see if they're equal.
736#[unstable(feature = "proc_macro_span", issue = "54725")]
737pub fn eq(&self, other: &Span) -> bool {
738self.0 == other.0
739}
740741/// Returns the source text behind a span. This preserves the original source
742 /// code, including spaces and comments. It only returns a result if the span
743 /// corresponds to real source code.
744 ///
745 /// Note: The observable result of a macro should only rely on the tokens and
746 /// not on this source text. The result of this function is a best effort to
747 /// be used for diagnostics only.
748#[stable(feature = "proc_macro_source_text", since = "1.66.0")]
749pub fn source_text(&self) -> Option<String> {
750BridgeMethods::span_source_text(self.0)
751 }
752753// Used by the implementation of `Span::quote`
754#[doc(hidden)]
755 #[unstable(feature = "proc_macro_internals", issue = "none")]
756pub fn save_span(&self) -> usize {
757BridgeMethods::span_save_span(self.0)
758 }
759760// Used by the implementation of `Span::quote`
761#[doc(hidden)]
762 #[unstable(feature = "proc_macro_internals", issue = "none")]
763pub fn recover_proc_macro_span(id: usize) -> Span {
764Span(BridgeMethods::span_recover_proc_macro_span(id))
765 }
766767/// 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);
768/// 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);
769/// 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);
770/// 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);
771}
772773/// Prints a span in a form convenient for debugging.
774#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
775impl fmt::Debugfor Span {
776fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
777self.0.fmt(f)
778 }
779}
780781/// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
782#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
783#[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)]
784pub enum TokenTree {
785/// A token stream surrounded by bracket delimiters.
786#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
787Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
788/// An identifier.
789#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
790Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
791/// A single punctuation character (`+`, `,`, `$`, etc.).
792#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
793Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
794/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
795#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
796Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
797}
798799#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
800impl !Sendfor TokenTree {}
801#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
802impl !Syncfor TokenTree {}
803804impl TokenTree {
805/// Returns the span of this tree, delegating to the `span` method of
806 /// the contained token or a delimited stream.
807#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
808pub fn span(&self) -> Span {
809match *self {
810 TokenTree::Group(ref t) => t.span(),
811 TokenTree::Ident(ref t) => t.span(),
812 TokenTree::Punct(ref t) => t.span(),
813 TokenTree::Literal(ref t) => t.span(),
814 }
815 }
816817/// Configures the span for *only this token*.
818 ///
819 /// Note that if this token is a `Group` then this method will not configure
820 /// the span of each of the internal tokens, this will simply delegate to
821 /// the `set_span` method of each variant.
822#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
823pub fn set_span(&mut self, span: Span) {
824match *self {
825 TokenTree::Group(ref mut t) => t.set_span(span),
826 TokenTree::Ident(ref mut t) => t.set_span(span),
827 TokenTree::Punct(ref mut t) => t.set_span(span),
828 TokenTree::Literal(ref mut t) => t.set_span(span),
829 }
830 }
831}
832833/// Prints token tree in a form convenient for debugging.
834#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
835impl fmt::Debugfor TokenTree {
836fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
837// Each of these has the name in the struct type in the derived debug,
838 // so don't bother with an extra layer of indirection
839match *self {
840 TokenTree::Group(ref tt) => tt.fmt(f),
841 TokenTree::Ident(ref tt) => tt.fmt(f),
842 TokenTree::Punct(ref tt) => tt.fmt(f),
843 TokenTree::Literal(ref tt) => tt.fmt(f),
844 }
845 }
846}
847848#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
849impl From<Group> for TokenTree {
850fn from(g: Group) -> TokenTree {
851 TokenTree::Group(g)
852 }
853}
854855#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
856impl From<Ident> for TokenTree {
857fn from(g: Ident) -> TokenTree {
858 TokenTree::Ident(g)
859 }
860}
861862#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
863impl From<Punct> for TokenTree {
864fn from(g: Punct) -> TokenTree {
865 TokenTree::Punct(g)
866 }
867}
868869#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
870impl From<Literal> for TokenTree {
871fn from(g: Literal) -> TokenTree {
872 TokenTree::Literal(g)
873 }
874}
875876/// Prints the token tree as a string that is supposed to be losslessly convertible back
877/// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
878/// with `Delimiter::None` delimiters and negative numeric literals.
879///
880/// Note: the exact form of the output is subject to change, e.g. there might
881/// be changes in the whitespace used between tokens. Therefore, you should
882/// *not* do any kind of simple substring matching on the output string (as
883/// produced by `to_string`) to implement a proc macro, because that matching
884/// might stop working if such changes happen. Instead, you should work at the
885/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
886/// `TokenTree::Punct`, or `TokenTree::Literal`.
887#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
888impl fmt::Displayfor TokenTree {
889fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
890match self {
891 TokenTree::Group(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
892 TokenTree::Ident(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
893 TokenTree::Punct(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
894 TokenTree::Literal(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
895 }
896 }
897}
898899/// A delimited token stream.
900///
901/// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
902#[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)]
903#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
904pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
905906#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
907impl !Sendfor Group {}
908#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
909impl !Syncfor Group {}
910911/// Describes how a sequence of token trees is delimited.
912#[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)]
913#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
914pub enum Delimiter {
915/// `( ... )`
916#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
917Parenthesis,
918/// `{ ... }`
919#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
920Brace,
921/// `[ ... ]`
922#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
923Bracket,
924/// `∅ ... ∅`
925 /// An invisible delimiter, that may, for example, appear around tokens coming from a
926 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
927 /// `$var * 3` where `$var` is `1 + 2`.
928 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
929 ///
930 /// <div class="warning">
931 ///
932 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
933 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
934 /// of a proc_macro macro are preserved, and only in very specific circumstances.
935 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
936 /// operator priorities as indicated above. The other `Delimiter` variants should be used
937 /// instead in this context. This is a rustc bug. For details, see
938 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
939 ///
940 /// </div>
941#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
942None,
943}
944945impl Group {
946/// Creates a new `Group` with the given delimiter and token stream.
947 ///
948 /// This constructor will set the span for this group to
949 /// `Span::call_site()`. To change the span you can use the `set_span`
950 /// method below.
951#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
952pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
953Group(bridge::Group {
954delimiter,
955 stream: stream.0,
956 span: bridge::DelimSpan::from_single(Span::call_site().0),
957 })
958 }
959960/// Returns the delimiter of this `Group`
961#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
962pub fn delimiter(&self) -> Delimiter {
963self.0.delimiter
964 }
965966/// Returns the `TokenStream` of tokens that are delimited in this `Group`.
967 ///
968 /// Note that the returned token stream does not include the delimiter
969 /// returned above.
970#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
971pub fn stream(&self) -> TokenStream {
972TokenStream(self.0.stream.clone())
973 }
974975/// Returns the span for the delimiters of this token stream, spanning the
976 /// entire `Group`.
977 ///
978 /// ```text
979 /// pub fn span(&self) -> Span {
980 /// ^^^^^^^
981 /// ```
982#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
983pub fn span(&self) -> Span {
984Span(self.0.span.entire)
985 }
986987/// Returns the span pointing to the opening delimiter of this group.
988 ///
989 /// ```text
990 /// pub fn span_open(&self) -> Span {
991 /// ^
992 /// ```
993#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
994pub fn span_open(&self) -> Span {
995Span(self.0.span.open)
996 }
997998/// Returns the span pointing to the closing delimiter of this group.
999 ///
1000 /// ```text
1001 /// pub fn span_close(&self) -> Span {
1002 /// ^
1003 /// ```
1004#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
1005pub fn span_close(&self) -> Span {
1006Span(self.0.span.close)
1007 }
10081009/// Configures the span for this `Group`'s delimiters, but not its internal
1010 /// tokens.
1011 ///
1012 /// This method will **not** set the span of all the internal tokens spanned
1013 /// by this group, but rather it will only set the span of the delimiter
1014 /// tokens at the level of the `Group`.
1015#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1016pub fn set_span(&mut self, span: Span) {
1017self.0.span = bridge::DelimSpan::from_single(span.0);
1018 }
1019}
10201021/// Prints the group as a string that should be losslessly convertible back
1022/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
1023/// with `Delimiter::None` delimiters.
1024#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1025impl fmt::Displayfor Group {
1026fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027f.write_fmt(format_args!("{0}",
TokenStream::from(TokenTree::from(self.clone()))))write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))1028 }
1029}
10301031#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1032impl fmt::Debugfor Group {
1033fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1034f.debug_struct("Group")
1035 .field("delimiter", &self.delimiter())
1036 .field("stream", &self.stream())
1037 .field("span", &self.span())
1038 .finish()
1039 }
1040}
10411042/// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
1043///
1044/// Multi-character operators like `+=` are represented as two instances of `Punct` with different
1045/// forms of `Spacing` returned.
1046#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1047#[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)]
1048pub struct Punct(bridge::Punct<bridge::client::Span>);
10491050#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1051impl !Sendfor Punct {}
1052#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1053impl !Syncfor Punct {}
10541055/// Indicates whether a `Punct` token can join with the following token
1056/// to form a multi-character operator.
1057#[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)]
1058#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1059pub enum Spacing {
1060/// A `Punct` token can join with the following token to form a multi-character operator.
1061 ///
1062 /// In token streams constructed using proc macro interfaces, `Joint` punctuation tokens can be
1063 /// followed by any other tokens. However, in token streams parsed from source code, the
1064 /// compiler will only set spacing to `Joint` in the following cases.
1065 /// - When a `Punct` is immediately followed by another `Punct` without a whitespace. E.g. `+`
1066 /// is `Joint` in `+=` and `++`.
1067 /// - When a single quote `'` is immediately followed by an identifier without a whitespace.
1068 /// E.g. `'` is `Joint` in `'lifetime`.
1069 ///
1070 /// This list may be extended in the future to enable more token combinations.
1071#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1072Joint,
1073/// A `Punct` token cannot join with the following token to form a multi-character operator.
1074 ///
1075 /// `Alone` punctuation tokens can be followed by any other tokens. In token streams parsed
1076 /// from source code, the compiler will set spacing to `Alone` in all cases not covered by the
1077 /// conditions for `Joint` above. E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`. In
1078 /// particular, tokens not followed by anything will be marked as `Alone`.
1079#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1080Alone,
1081}
10821083impl Punct {
1084/// Creates a new `Punct` from the given character and spacing.
1085 /// The `ch` argument must be a valid punctuation character permitted by the language,
1086 /// otherwise the function will panic.
1087 ///
1088 /// The returned `Punct` will have the default span of `Span::call_site()`
1089 /// which can be further configured with the `set_span` method below.
1090#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1091pub fn new(ch: char, spacing: Spacing) -> Punct {
1092const LEGAL_CHARS: &[char] = &[
1093'=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
1094':', '#', '$', '?', '\'',
1095 ];
1096if !LEGAL_CHARS.contains(&ch) {
1097{
::core::panicking::panic_fmt(format_args!("unsupported character `{0:?}`",
ch));
};panic!("unsupported character `{:?}`", ch);
1098 }
1099Punct(bridge::Punct {
1100 ch: chas u8,
1101 joint: spacing == Spacing::Joint,
1102 span: Span::call_site().0,
1103 })
1104 }
11051106/// Returns the value of this punctuation character as `char`.
1107#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1108pub fn as_char(&self) -> char {
1109self.0.ch as char1110 }
11111112/// Returns the spacing of this punctuation character, indicating whether it can be potentially
1113 /// combined into a multi-character operator with the following token (`Joint`), or whether the
1114 /// operator has definitely ended (`Alone`).
1115#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1116pub fn spacing(&self) -> Spacing {
1117if self.0.joint { Spacing::Joint } else { Spacing::Alone }
1118 }
11191120/// Returns the span for this punctuation character.
1121#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1122pub fn span(&self) -> Span {
1123Span(self.0.span)
1124 }
11251126/// Configure the span for this punctuation character.
1127#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1128pub fn set_span(&mut self, span: Span) {
1129self.0.span = span.0;
1130 }
1131}
11321133/// Prints the punctuation character as a string that should be losslessly convertible
1134/// back into the same character.
1135#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1136impl fmt::Displayfor Punct {
1137fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138f.write_fmt(format_args!("{0}", self.as_char()))write!(f, "{}", self.as_char())1139 }
1140}
11411142#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1143impl fmt::Debugfor Punct {
1144fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1145f.debug_struct("Punct")
1146 .field("ch", &self.as_char())
1147 .field("spacing", &self.spacing())
1148 .field("span", &self.span())
1149 .finish()
1150 }
1151}
11521153#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1154impl PartialEq<char> for Punct {
1155fn eq(&self, rhs: &char) -> bool {
1156self.as_char() == *rhs1157 }
1158}
11591160#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1161impl PartialEq<Punct> for char {
1162fn eq(&self, rhs: &Punct) -> bool {
1163*self == rhs.as_char()
1164 }
1165}
11661167/// An identifier (`ident`).
1168#[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)]
1169#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1170pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
11711172impl Ident {
1173/// Creates a new `Ident` with the given `string` as well as the specified
1174 /// `span`.
1175 /// The `string` argument must be a valid identifier permitted by the
1176 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1177 ///
1178 /// The constructed identifier will be NFC-normalized. See the [Reference] for more info.
1179 ///
1180 /// Note that `span`, currently in rustc, configures the hygiene information
1181 /// for this identifier.
1182 ///
1183 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1184 /// meaning that identifiers created with this span will be resolved as if they were written
1185 /// directly at the location of the macro call, and other code at the macro call site will be
1186 /// able to refer to them as well.
1187 ///
1188 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1189 /// meaning that identifiers created with this span will be resolved at the location of the
1190 /// macro definition and other code at the macro call site will not be able to refer to them.
1191 ///
1192 /// Due to the current importance of hygiene this constructor, unlike other
1193 /// tokens, requires a `Span` to be specified at construction.
1194 ///
1195 /// [Reference]: https://doc.rust-lang.org/nightly/reference/identifiers.html#r-ident.normalization
1196#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1197pub fn new(string: &str, span: Span) -> Ident {
1198Ident(bridge::Ident {
1199 sym: bridge::client::Symbol::new_ident(string, false),
1200 is_raw: false,
1201 span: span.0,
1202 })
1203 }
12041205/// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1206 /// The `string` argument be a valid identifier permitted by the language
1207 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1208 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1209#[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1210pub fn new_raw(string: &str, span: Span) -> Ident {
1211Ident(bridge::Ident {
1212 sym: bridge::client::Symbol::new_ident(string, true),
1213 is_raw: true,
1214 span: span.0,
1215 })
1216 }
12171218/// Returns the span of this `Ident`, encompassing the entire string returned
1219 /// by [`to_string`](ToString::to_string).
1220#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1221pub fn span(&self) -> Span {
1222Span(self.0.span)
1223 }
12241225/// Configures the span of this `Ident`, possibly changing its hygiene context.
1226#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1227pub fn set_span(&mut self, span: Span) {
1228self.0.span = span.0;
1229 }
1230}
12311232/// Prints the identifier as a string that should be losslessly convertible back
1233/// into the same identifier.
1234#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1235impl fmt::Displayfor Ident {
1236fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1237if self.0.is_raw {
1238 f.write_str("r#")?;
1239 }
1240 fmt::Display::fmt(&self.0.sym, f)
1241 }
1242}
12431244#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1245impl fmt::Debugfor Ident {
1246fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1247f.debug_struct("Ident")
1248 .field("ident", &self.to_string())
1249 .field("span", &self.span())
1250 .finish()
1251 }
1252}
12531254/// A literal string (`"hello"`), byte string (`b"hello"`), C string (`c"hello"`),
1255/// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1256/// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1257/// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1258#[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)]
1259#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1260pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
12611262macro_rules!suffixed_int_literals {
1263 ($($name:ident => $kind:ident,)*) => ($(
1264/// Creates a new suffixed integer literal with the specified value.
1265 ///
1266 /// This function will create an integer like `1u32` where the integer
1267 /// value specified is the first part of the token and the integral is
1268 /// also suffixed at the end.
1269 /// Literals created from negative numbers might not survive round-trips through
1270 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1271 ///
1272 /// Literals created through this method have the `Span::call_site()`
1273 /// span by default, which can be configured with the `set_span` method
1274 /// below.
1275#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1276pub fn $name(n: $kind) -> Literal {
1277 Literal(bridge::Literal {
1278 kind: bridge::LitKind::Integer,
1279 symbol: bridge::client::Symbol::new(&n.to_string()),
1280 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1281 span: Span::call_site().0,
1282 })
1283 }
1284 )*)
1285}
12861287macro_rules!unsuffixed_int_literals {
1288 ($($name:ident => $kind:ident,)*) => ($(
1289/// Creates a new unsuffixed integer literal with the specified value.
1290 ///
1291 /// This function will create an integer like `1` where the integer
1292 /// value specified is the first part of the token. No suffix is
1293 /// specified on this token, meaning that invocations like
1294 /// `Literal::i8_unsuffixed(1)` are equivalent to
1295 /// `Literal::u32_unsuffixed(1)`.
1296 /// Literals created from negative numbers might not survive roundtrips through
1297 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1298 ///
1299 /// Literals created through this method have the `Span::call_site()`
1300 /// span by default, which can be configured with the `set_span` method
1301 /// below.
1302#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1303pub fn $name(n: $kind) -> Literal {
1304 Literal(bridge::Literal {
1305 kind: bridge::LitKind::Integer,
1306 symbol: bridge::client::Symbol::new(&n.to_string()),
1307 suffix: None,
1308 span: Span::call_site().0,
1309 })
1310 }
1311 )*)
1312}
13131314macro_rules!integer_values {
1315 ($($nb:ident => $fn_name:ident,)+) => {
1316 $(
1317#[doc = concat!(
1318"Returns the unescaped `",
1319stringify!($nb),
1320"` value if the literal is a `",
1321stringify!($nb),
1322"` or if it's an \"unmarked\" integer which doesn't overflow.")]
1323 #[unstable(feature = "proc_macro_value", issue = "136652")]
1324pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1325if self.0.kind != bridge::LitKind::Integer {
1326return Err(ConversionErrorKind::InvalidLiteralKind);
1327 }
1328self.with_symbol_and_suffix(|symbol, suffix| {
1329match suffix {
1330stringify!($nb) | "" => {
1331let symbol = strip_underscores(symbol);
1332let (number, base) = parse_number(&symbol);
1333$nb::from_str_radix(&number, base as u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1334 }
1335_ => Err(ConversionErrorKind::InvalidLiteralKind),
1336 }
1337 })
1338 }
1339 )+
1340 }
1341}
13421343macro_rules!float_values {
1344 ($($nb:ident => $fn_name:ident,)+) => {
1345 $(
1346#[doc = concat!(
1347"Returns the unescaped `",
1348stringify!($nb),
1349"` value if the literal is a `",
1350stringify!($nb),
1351"` or if it's an \"unmarked\" float which doesn't overflow.")]
1352 #[unstable(feature = "proc_macro_value", issue = "136652")]
1353pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1354if self.0.kind != bridge::LitKind::Float {
1355return Err(ConversionErrorKind::InvalidLiteralKind);
1356 }
1357self.with_symbol_and_suffix(|symbol, suffix| {
1358match suffix {
1359stringify!($nb) | "" => {
1360let number = strip_underscores(symbol);
1361$nb::from_str(&number).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1362 }
1363_ => Err(ConversionErrorKind::InvalidLiteralKind),
1364 }
1365 })
1366 }
1367 )+
1368 }
1369}
13701371impl Literal {
1372fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1373Literal(bridge::Literal {
1374kind,
1375 symbol: bridge::client::Symbol::new(value),
1376 suffix: suffix.map(bridge::client::Symbol::new),
1377 span: Span::call_site().0,
1378 })
1379 }
13801381/// 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! {
1382 u8_suffixed => u8,
1383 u16_suffixed => u16,
1384 u32_suffixed => u32,
1385 u64_suffixed => u64,
1386 u128_suffixed => u128,
1387 usize_suffixed => usize,
1388 i8_suffixed => i8,
1389 i16_suffixed => i16,
1390 i32_suffixed => i32,
1391 i64_suffixed => i64,
1392 i128_suffixed => i128,
1393 isize_suffixed => isize,
1394 }13951396/// 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! {
1397 u8_unsuffixed => u8,
1398 u16_unsuffixed => u16,
1399 u32_unsuffixed => u32,
1400 u64_unsuffixed => u64,
1401 u128_unsuffixed => u128,
1402 usize_unsuffixed => usize,
1403 i8_unsuffixed => i8,
1404 i16_unsuffixed => i16,
1405 i32_unsuffixed => i32,
1406 i64_unsuffixed => i64,
1407 i128_unsuffixed => i128,
1408 isize_unsuffixed => isize,
1409 }14101411/// Creates a new unsuffixed floating-point literal.
1412 ///
1413 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1414 /// the float's value is emitted directly into the token but no suffix is
1415 /// used, so it may be inferred to be a `f64` later in the compiler.
1416 /// Literals created from negative numbers might not survive roundtrips through
1417 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1418 ///
1419 /// # Panics
1420 ///
1421 /// This function requires that the specified float is finite, for
1422 /// example if it is infinity or NaN this function will panic.
1423#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1424pub fn f32_unsuffixed(n: f32) -> Literal {
1425if !n.is_finite() {
1426{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1427 }
1428let mut repr = n.to_string();
1429if !repr.contains('.') {
1430repr.push_str(".0");
1431 }
1432Literal::new(bridge::LitKind::Float, &repr, None)
1433 }
14341435/// Creates a new suffixed floating-point literal.
1436 ///
1437 /// This constructor will create a literal like `1.0f32` where the value
1438 /// specified is the preceding part of the token and `f32` is the suffix of
1439 /// the token. This token will always be inferred to be an `f32` in the
1440 /// compiler.
1441 /// Literals created from negative numbers might not survive roundtrips through
1442 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1443 ///
1444 /// # Panics
1445 ///
1446 /// This function requires that the specified float is finite, for
1447 /// example if it is infinity or NaN this function will panic.
1448#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1449pub fn f32_suffixed(n: f32) -> Literal {
1450if !n.is_finite() {
1451{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1452 }
1453Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1454 }
14551456/// Creates a new unsuffixed floating-point literal.
1457 ///
1458 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1459 /// the float's value is emitted directly into the token but no suffix is
1460 /// used, so it may be inferred to be a `f64` later in the compiler.
1461 /// Literals created from negative numbers might not survive roundtrips through
1462 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1463 ///
1464 /// # Panics
1465 ///
1466 /// This function requires that the specified float is finite, for
1467 /// example if it is infinity or NaN this function will panic.
1468#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1469pub fn f64_unsuffixed(n: f64) -> Literal {
1470if !n.is_finite() {
1471{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1472 }
1473let mut repr = n.to_string();
1474if !repr.contains('.') {
1475repr.push_str(".0");
1476 }
1477Literal::new(bridge::LitKind::Float, &repr, None)
1478 }
14791480/// Creates a new suffixed floating-point literal.
1481 ///
1482 /// This constructor will create a literal like `1.0f64` where the value
1483 /// specified is the preceding part of the token and `f64` is the suffix of
1484 /// the token. This token will always be inferred to be an `f64` in the
1485 /// compiler.
1486 /// Literals created from negative numbers might not survive roundtrips through
1487 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1488 ///
1489 /// # Panics
1490 ///
1491 /// This function requires that the specified float is finite, for
1492 /// example if it is infinity or NaN this function will panic.
1493#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1494pub fn f64_suffixed(n: f64) -> Literal {
1495if !n.is_finite() {
1496{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1497 }
1498Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1499 }
15001501/// String literal.
1502#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1503pub fn string(string: &str) -> Literal {
1504let escape = EscapeOptions {
1505 escape_single_quote: false,
1506 escape_double_quote: true,
1507 escape_nonascii: false,
1508 };
1509let repr = escape_bytes(string.as_bytes(), escape);
1510Literal::new(bridge::LitKind::Str, &repr, None)
1511 }
15121513/// Character literal.
1514#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1515pub fn character(ch: char) -> Literal {
1516let escape = EscapeOptions {
1517 escape_single_quote: true,
1518 escape_double_quote: false,
1519 escape_nonascii: false,
1520 };
1521let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1522Literal::new(bridge::LitKind::Char, &repr, None)
1523 }
15241525/// Byte character literal.
1526#[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1527pub fn byte_character(byte: u8) -> Literal {
1528let escape = EscapeOptions {
1529 escape_single_quote: true,
1530 escape_double_quote: false,
1531 escape_nonascii: true,
1532 };
1533let repr = escape_bytes(&[byte], escape);
1534Literal::new(bridge::LitKind::Byte, &repr, None)
1535 }
15361537/// Byte string literal.
1538#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1539pub fn byte_string(bytes: &[u8]) -> Literal {
1540let escape = EscapeOptions {
1541 escape_single_quote: false,
1542 escape_double_quote: true,
1543 escape_nonascii: true,
1544 };
1545let repr = escape_bytes(bytes, escape);
1546Literal::new(bridge::LitKind::ByteStr, &repr, None)
1547 }
15481549/// C string literal.
1550#[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1551pub fn c_string(string: &CStr) -> Literal {
1552let escape = EscapeOptions {
1553 escape_single_quote: false,
1554 escape_double_quote: true,
1555 escape_nonascii: false,
1556 };
1557let repr = escape_bytes(string.to_bytes(), escape);
1558Literal::new(bridge::LitKind::CStr, &repr, None)
1559 }
15601561/// Returns the span encompassing this literal.
1562#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1563pub fn span(&self) -> Span {
1564Span(self.0.span)
1565 }
15661567/// Configures the span associated for this literal.
1568#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1569pub fn set_span(&mut self, span: Span) {
1570self.0.span = span.0;
1571 }
15721573/// Returns a `Span` that is a subset of `self.span()` containing only the
1574 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1575 /// span is outside the bounds of `self`.
1576// FIXME(SergioBenitez): check that the byte range starts and ends at a
1577 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1578 // occur elsewhere when the source text is printed.
1579 // FIXME(SergioBenitez): there is no way for the user to know what
1580 // `self.span()` actually maps to, so this method can currently only be
1581 // called blindly. For example, `to_string()` for the character 'c' returns
1582 // "'\u{63}'"; there is no way for the user to know whether the source text
1583 // was 'c' or whether it was '\u{63}'.
1584#[unstable(feature = "proc_macro_span", issue = "54725")]
1585pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1586BridgeMethods::span_subspan(
1587self.0.span,
1588range.start_bound().cloned(),
1589range.end_bound().cloned(),
1590 )
1591 .map(Span)
1592 }
15931594fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1595self.0.symbol.with(|symbol| match self.0.suffix {
1596Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1597None => f(symbol, ""),
1598 })
1599 }
16001601/// Invokes the callback with a `&[&str]` consisting of each part of the
1602 /// literal's representation. This is done to allow the `ToString` and
1603 /// `Display` implementations to borrow references to symbol values, and
1604 /// both be optimized to reduce overhead.
1605fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1606/// Returns a string containing exactly `num` '#' characters.
1607 /// Uses a 256-character source string literal which is always safe to
1608 /// index with a `u8` index.
1609fn get_hashes_str(num: u8) -> &'static str {
1610const HASHES: &str = "\
1611 ################################################################\
1612 ################################################################\
1613 ################################################################\
1614 ################################################################\
1615 ";
1616const _: () = if !(HASHES.len() == 256) {
::core::panicking::panic("assertion failed: HASHES.len() == 256")
}assert!(HASHES.len() == 256);
1617&HASHES[..num as usize]
1618 }
16191620self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1621 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1622 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1623 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1624 bridge::LitKind::StrRaw(n) => {
1625let hashes = get_hashes_str(n);
1626f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1627 }
1628 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1629 bridge::LitKind::ByteStrRaw(n) => {
1630let hashes = get_hashes_str(n);
1631f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1632 }
1633 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1634 bridge::LitKind::CStrRaw(n) => {
1635let hashes = get_hashes_str(n);
1636f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1637 }
16381639 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1640f(&[symbol, suffix])
1641 }
1642 })
1643 }
16441645/// Returns the unescaped character value if the current literal is a byte character literal.
1646#[unstable(feature = "proc_macro_value", issue = "136652")]
1647pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1648self.0.symbol.with(|symbol| match self.0.kind {
1649 bridge::LitKind::Byte => unescape_byte(symbol)
1650 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1651_ => Err(ConversionErrorKind::InvalidLiteralKind),
1652 })
1653 }
16541655/// Returns the unescaped character value if the current literal is a character literal.
1656#[unstable(feature = "proc_macro_value", issue = "136652")]
1657pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1658self.0.symbol.with(|symbol| match self.0.kind {
1659 bridge::LitKind::Char => unescape_char(symbol)
1660 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1661_ => Err(ConversionErrorKind::InvalidLiteralKind),
1662 })
1663 }
16641665/// Returns the unescaped string value if the current literal is a string or a string literal.
1666#[unstable(feature = "proc_macro_value", issue = "136652")]
1667pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1668self.0.symbol.with(|symbol| match self.0.kind {
1669 bridge::LitKind::Str => {
1670if symbol.contains('\\') {
1671let mut buf = String::with_capacity(symbol.len());
1672let mut error = None;
1673// Force-inlining here is aggressive but the closure is
1674 // called on every char in the string, so it can be hot in
1675 // programs with many long strings containing escapes.
1676unescape_str(
1677symbol,
1678#[inline(always)]
1679|_, c| match c {
1680Ok(c) => buf.push(c),
1681Err(err) => {
1682if err.is_fatal() {
1683error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1684 }
1685 }
1686 },
1687 );
1688if let Some(error) = error { Err(error) } else { Ok(buf) }
1689 } else {
1690Ok(symbol.to_string())
1691 }
1692 }
1693 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1694_ => Err(ConversionErrorKind::InvalidLiteralKind),
1695 })
1696 }
16971698/// Returns the unescaped string value if the current literal is a c-string or a c-string
1699 /// literal.
1700#[unstable(feature = "proc_macro_value", issue = "136652")]
1701pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1702self.0.symbol.with(|symbol| match self.0.kind {
1703 bridge::LitKind::CStr => {
1704let mut error = None;
1705let mut buf = Vec::with_capacity(symbol.len());
17061707unescape_c_str(symbol, |_span, res| match res {
1708Ok(MixedUnit::Char(c)) => {
1709buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1710 }
1711Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1712Err(err) => {
1713if err.is_fatal() {
1714error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1715 }
1716 }
1717 });
1718if let Some(error) = error {
1719Err(error)
1720 } else {
1721buf.push(0);
1722Ok(buf)
1723 }
1724 }
1725 bridge::LitKind::CStrRaw(_) => {
1726// Raw strings have no escapes so we can convert the symbol
1727 // directly to a `Lrc<u8>` after appending the terminating NUL
1728 // char.
1729let mut buf = symbol.to_owned().into_bytes();
1730buf.push(0);
1731Ok(buf)
1732 }
1733_ => Err(ConversionErrorKind::InvalidLiteralKind),
1734 })
1735 }
17361737/// Returns the unescaped string value if the current literal is a byte string or a byte string
1738 /// literal.
1739#[unstable(feature = "proc_macro_value", issue = "136652")]
1740pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1741self.0.symbol.with(|symbol| match self.0.kind {
1742 bridge::LitKind::ByteStr => {
1743let mut buf = Vec::with_capacity(symbol.len());
1744let mut error = None;
17451746unescape_byte_str(symbol, |_, res| match res {
1747Ok(b) => buf.push(b),
1748Err(err) => {
1749if err.is_fatal() {
1750error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1751 }
1752 }
1753 });
1754if let Some(error) = error { Err(error) } else { Ok(buf) }
1755 }
1756 bridge::LitKind::ByteStrRaw(_) => {
1757// Raw strings have no escapes so we can convert the symbol
1758 // directly to a `Lrc<u8>`.
1759Ok(symbol.to_owned().into_bytes())
1760 }
1761_ => Err(ConversionErrorKind::InvalidLiteralKind),
1762 })
1763 }
17641765#[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! {
1766 u8 => u8_value,
1767 u16 => u16_value,
1768 u32 => u32_value,
1769 u64 => u64_value,
1770 u128 => u128_value,
1771 i8 => i8_value,
1772 i16 => i16_value,
1773 i32 => i32_value,
1774 i64 => i64_value,
1775 i128 => i128_value,
1776 }17771778#[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! {
1779 f16 => f16_value,
1780 f32 => f32_value,
1781 f64 => f64_value,
1782// FIXME: `f128` doesn't implement `FromStr` for the moment so we cannot obtain it from
1783 // a `&str`. To be uncommented when it's added.
1784 // f128 => f128_value,
1785}1786}
17871788#[repr(u32)]
1789#[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)]
1790enum Base {
1791 Decimal = 10,
1792 Binary = 2,
1793 Octal = 8,
1794 Hexadecimal = 16,
1795}
17961797fn parse_number(value: &str) -> (&str, Base) {
1798let mut iter = value.as_bytes().iter().copied();
1799let Some(first_digit) = iter.next() else {
1800return ("0", Base::Decimal);
1801 };
1802let Some(second_digit) = iter.next() else {
1803return (value, Base::Decimal);
1804 };
18051806let mut base = Base::Decimal;
1807if first_digit == b'0' {
1808// Attempt to parse encoding base.
1809match second_digit {
1810b'b' => {
1811base = Base::Binary;
1812 }
1813b'o' => {
1814base = Base::Octal;
1815 }
1816b'x' => {
1817base = Base::Hexadecimal;
1818 }
1819_ => {}
1820 }
1821 }
18221823let offset = if base == Base::Decimal { 0 } else { 2 };
18241825 (&value[offset..], base)
1826}
18271828fn strip_underscores(value_s: &str) -> Cow<'_, str> {
1829let value = value_s.as_bytes();
1830if value.iter().copied().all(|c| c != b'_' && c != b'f') {
1831return Cow::Borrowed(value_s);
1832 }
1833let mut output = String::with_capacity(value.len());
1834for c in value.iter().copied() {
1835if c != b'_' {
1836 output.push(c as char);
1837 }
1838 }
1839 Cow::Owned(output)
1840}
18411842/// Parse a single literal from its stringified representation.
1843///
1844/// In order to parse successfully, the input string must not contain anything
1845/// but the literal token. Specifically, it must not contain whitespace or
1846/// comments in addition to the literal.
1847///
1848/// The resulting literal token will have a `Span::call_site()` span.
1849///
1850/// NOTE: some errors may cause panics instead of returning `LexError`. We
1851/// reserve the right to change these errors into `LexError`s later.
1852#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1853impl FromStrfor Literal {
1854type Err = LexError;
18551856fn from_str(src: &str) -> Result<Self, LexError> {
1857match BridgeMethods::literal_from_str(src) {
1858Ok(literal) => Ok(Literal(literal)),
1859Err(msg) => Err(LexError(msg)),
1860 }
1861 }
1862}
18631864/// Prints the literal as a string that should be losslessly convertible
1865/// back into the same literal (except for possible rounding for floating point literals).
1866#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1867impl fmt::Displayfor Literal {
1868fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1869self.with_stringify_parts(|parts| {
1870for part in parts {
1871 fmt::Display::fmt(part, f)?;
1872 }
1873Ok(())
1874 })
1875 }
1876}
18771878#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1879impl fmt::Debugfor Literal {
1880fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1881f.debug_struct("Literal")
1882// format the kind on one line even in {:#?} mode
1883 .field("kind", &format_args!("{0:?}", self.0.kind)format_args!("{:?}", self.0.kind))
1884 .field("symbol", &self.0.symbol)
1885// format `Some("...")` on one line even in {:#?} mode
1886 .field("suffix", &format_args!("{0:?}", self.0.suffix)format_args!("{:?}", self.0.suffix))
1887 .field("span", &self.0.span)
1888 .finish()
1889 }
1890}
18911892#[unstable(
1893 feature = "proc_macro_tracked_path",
1894 issue = "99515",
1895 implied_by = "proc_macro_tracked_env"
1896)]
1897/// Functionality for adding environment state to the build dependency info.
1898pub mod tracked {
1899use std::env::{self, VarError};
1900use std::ffi::OsStr;
1901use std::path::Path;
19021903use crate::BridgeMethods;
19041905/// Retrieve an environment variable and add it to build dependency info.
1906 /// The build system executing the compiler will know that the variable was accessed during
1907 /// compilation, and will be able to rerun the build when the value of that variable changes.
1908 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1909 /// standard library, except that the argument must be UTF-8.
1910#[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1911pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1912let key: &str = key.as_ref();
1913let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1914BridgeMethods::track_env_var(key, value.as_deref().ok());
1915value1916 }
19171918/// Track a file or directory explicitly.
1919 ///
1920 /// Commonly used for tracking asset preprocessing.
1921#[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1922pub fn path<P: AsRef<Path>>(path: P) {
1923let path: &str = path.as_ref().to_str().unwrap();
1924BridgeMethods::track_path(path);
1925 }
1926}