1//! A support library for macro authors when defining new macros.
2//!
3//! This library, provided by the standard distribution, provides the types
4//! consumed in the interfaces of procedurally defined macro definitions such as
5//! function-like macros `#[proc_macro]`, macro attributes `#[proc_macro_attribute]` and
6//! custom derive attributes `#[proc_macro_derive]`.
7//!
8//! See [the book] for more.
9//!
10//! [the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes
1112#![stable(feature = "proc_macro_lib", since = "1.15.0")]
13#![deny(missing_docs)]
14#![doc(
15 html_playground_url = "https://play.rust-lang.org/",
16 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
17 test(no_crate_inject, attr(deny(warnings))),
18 test(attr(allow(dead_code, deprecated, unused_variables, unused_mut)))
19)]
20#![doc(rust_logo)]
21#![feature(rustdoc_internals)]
22#![feature(staged_api)]
23#![feature(allow_internal_unstable)]
24#![feature(decl_macro)]
25#![feature(negative_impls)]
26#![feature(panic_can_unwind)]
27#![feature(restricted_std)]
28#![feature(rustc_attrs)]
29#![feature(extend_one)]
30#![feature(f16)]
31#![recursion_limit = "256"]
32#![allow(internal_features)]
33#![deny(ffi_unwind_calls)]
34#![allow(rustc::internal)] // Can't use FxHashMap when compiled as part of the standard library
35#![warn(rustdoc::unescaped_backticks)]
36#![warn(unreachable_pub)]
37#![deny(unsafe_op_in_unsafe_fn)]
3839#[unstable(feature = "proc_macro_internals", issue = "none")]
40#[doc(hidden)]
41pub mod bridge;
4243mod diagnostic;
44mod escape;
45mod to_tokens;
4647use core::convert::From;
48use core::ops::BitOr;
49use std::borrow::Cow;
50use std::ffi::CStr;
51use std::ops::{Range, RangeBounds};
52use std::path::PathBuf;
53use std::str::FromStr;
54use std::{error, fmt};
5556#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
57pub use diagnostic::{Diagnostic, Level, MultiSpan};
58use rustc_literal_escaper::{
59MixedUnit, unescape_byte, unescape_byte_str, unescape_c_str, unescape_char, unescape_str,
60};
61#[unstable(feature = "proc_macro_totokens", issue = "130977")]
62pub use to_tokens::ToTokens;
6364use crate::bridge::client::Methodsas BridgeMethods;
65use crate::escape::{EscapeOptions, escape_bytes};
6667/// Mostly relating to malformed escape sequences, but also a few other problems.
68#[unstable(feature = "proc_macro_value", issue = "136652")]
69#[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::marker::StructuralPartialEq for EscapeError { }
#[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::PartialEq for EscapeError {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::Eq for EscapeError { }Eq)]
70#[non_exhaustive]
71pub enum EscapeError {
72/// Expected 1 char, but 0 were found.
73ZeroChars,
74/// Expected 1 char, but more than 1 were found.
75MoreThanOneChar,
7677/// Escaped '\' character without continuation.
78LoneSlash,
79/// Invalid escape character (e.g. '\z').
80InvalidEscape,
81/// Raw '\r' encountered.
82BareCarriageReturn,
83/// Raw '\r' encountered in raw string.
84BareCarriageReturnInRawString,
85/// Unescaped character that was expected to be escaped (e.g. raw '\t').
86EscapeOnlyChar,
8788/// Numeric character escape is too short (e.g. '\x1').
89TooShortHexEscape,
90/// Invalid character in numeric escape (e.g. '\xz')
91InvalidCharInHexEscape,
92/// Character code in numeric escape is non-ascii (e.g. '\xFF').
93OutOfRangeHexEscape,
9495/// '\u' not followed by '{'.
96NoBraceInUnicodeEscape,
97/// Non-hexadecimal value in '\u{..}'.
98InvalidCharInUnicodeEscape,
99/// '\u{}'
100EmptyUnicodeEscape,
101/// No closing brace in '\u{..}', e.g. '\u{12'.
102UnclosedUnicodeEscape,
103/// '\u{_12}'
104LeadingUnderscoreUnicodeEscape,
105/// More than 6 characters in '\u{..}', e.g. '\u{10FFFF_FF}'
106OverlongUnicodeEscape,
107/// Invalid in-bound unicode character code, e.g. '\u{DFFF}'.
108LoneSurrogateUnicodeEscape,
109/// Out of bounds unicode character code, e.g. '\u{FFFFFF}'.
110OutOfRangeUnicodeEscape,
111112/// Unicode escape code in byte literal.
113UnicodeEscapeInByte,
114/// Non-ascii character in byte literal, byte string literal, or raw byte string literal.
115NonAsciiCharInByte,
116117/// `\0` in a C string literal.
118NulInCStr,
119120/// After a line ending with '\', the next line contains whitespace
121 /// characters that are not skipped.
122UnskippedWhitespaceWarning,
123124/// After a line ending with '\', multiple lines are skipped.
125MultipleSkippedLinesWarning,
126}
127128#[unstable(feature = "proc_macro_value", issue = "136652")]
129#[doc(hidden)]
130impl From<rustc_literal_escaper::EscapeError> for EscapeError {
131fn from(value: rustc_literal_escaper::EscapeError) -> Self {
132use rustc_literal_escaper::EscapeErroras EE;
133134match value {
135 EE::ZeroChars => Self::ZeroChars,
136 EE::MoreThanOneChar => Self::MoreThanOneChar,
137 EE::LoneSlash => Self::LoneSlash,
138 EE::InvalidEscape => Self::InvalidEscape,
139 EE::BareCarriageReturn => Self::BareCarriageReturn,
140 EE::BareCarriageReturnInRawString => Self::BareCarriageReturnInRawString,
141 EE::EscapeOnlyChar => Self::EscapeOnlyChar,
142 EE::TooShortHexEscape => Self::TooShortHexEscape,
143 EE::InvalidCharInHexEscape => Self::InvalidCharInHexEscape,
144 EE::OutOfRangeHexEscape => Self::OutOfRangeHexEscape,
145 EE::NoBraceInUnicodeEscape => Self::NoBraceInUnicodeEscape,
146 EE::InvalidCharInUnicodeEscape => Self::InvalidCharInUnicodeEscape,
147 EE::EmptyUnicodeEscape => Self::EmptyUnicodeEscape,
148 EE::UnclosedUnicodeEscape => Self::UnclosedUnicodeEscape,
149 EE::LeadingUnderscoreUnicodeEscape => Self::LeadingUnderscoreUnicodeEscape,
150 EE::OverlongUnicodeEscape => Self::OverlongUnicodeEscape,
151 EE::LoneSurrogateUnicodeEscape => Self::LoneSurrogateUnicodeEscape,
152 EE::OutOfRangeUnicodeEscape => Self::OutOfRangeUnicodeEscape,
153 EE::UnicodeEscapeInByte => Self::UnicodeEscapeInByte,
154 EE::NonAsciiCharInByte => Self::NonAsciiCharInByte,
155 EE::NulInCStr => Self::NulInCStr,
156 EE::UnskippedWhitespaceWarning => Self::UnskippedWhitespaceWarning,
157 EE::MultipleSkippedLinesWarning => Self::MultipleSkippedLinesWarning,
158 }
159 }
160}
161162#[unstable(feature = "proc_macro_value", issue = "136652")]
163impl error::Errorfor EscapeError {}
164165#[unstable(feature = "proc_macro_value", issue = "136652")]
166impl fmt::Displayfor EscapeError {
167fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168f.write_str(match self {
169Self::ZeroChars => "zero chars",
170Self::MoreThanOneChar => "more than one char",
171Self::LoneSlash => "lone slash",
172Self::InvalidEscape => "invalid escape",
173Self::BareCarriageReturn => "bare carriage return",
174Self::BareCarriageReturnInRawString => "bare carriage return in raw string",
175Self::EscapeOnlyChar => "escape only char",
176Self::TooShortHexEscape => "too short hex escape",
177Self::InvalidCharInHexEscape => "invalid char in hex escape",
178Self::OutOfRangeHexEscape => "out of range hex escape",
179Self::NoBraceInUnicodeEscape => "no brace in unicode escape",
180Self::InvalidCharInUnicodeEscape => "invalid char in unicode escape",
181Self::EmptyUnicodeEscape => "empty unicode escape",
182Self::UnclosedUnicodeEscape => "unclosed unicode escape",
183Self::LeadingUnderscoreUnicodeEscape => "leading underscore unicode escape",
184Self::OverlongUnicodeEscape => "overlong unicode escape",
185Self::LoneSurrogateUnicodeEscape => "lone surrogate unicode escape",
186Self::OutOfRangeUnicodeEscape => "out of range unicode escape",
187Self::UnicodeEscapeInByte => "unicode escape in byte",
188Self::NonAsciiCharInByte => "non ascii char in byte",
189Self::NulInCStr => "nul in CStr",
190Self::UnskippedWhitespaceWarning => "unskipped whitespace warning",
191Self::MultipleSkippedLinesWarning => "multiple skipped lines warning",
192 })
193 }
194}
195196/// Errors returned when trying to retrieve a literal unescaped value.
197#[unstable(feature = "proc_macro_value", issue = "136652")]
198#[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 {
Self::FailedToUnescape(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FailedToUnescape", &__self_0),
Self::InvalidLiteralKind =>
::core::fmt::Formatter::write_str(f, "InvalidLiteralKind"),
}
}
}Debug, #[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::marker::StructuralPartialEq for ConversionErrorKind { }
#[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::PartialEq for ConversionErrorKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::FailedToUnescape(__self_0),
Self::FailedToUnescape(__arg1_0)) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
#[unstable(feature = "proc_macro_value", issue = "136652")]
impl ::core::cmp::Eq for ConversionErrorKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<EscapeError>;
}
}Eq)]
199#[non_exhaustive]
200pub enum ConversionErrorKind {
201/// The literal failed to be escaped, take a look at [`EscapeError`] for more information.
202FailedToUnescape(EscapeError),
203/// Trying to convert a literal with the wrong type.
204InvalidLiteralKind,
205}
206207/// Determines whether proc_macro has been made accessible to the currently
208/// running program.
209///
210/// The proc_macro crate is only intended for use inside the implementation of
211/// procedural macros. All the functions in this crate panic if invoked from
212/// outside of a procedural macro, such as from a build script or unit test or
213/// ordinary Rust binary.
214///
215/// With consideration for Rust libraries that are designed to support both
216/// macro and non-macro use cases, `proc_macro::is_available()` provides a
217/// non-panicking way to detect whether the infrastructure required to use the
218/// API of proc_macro is presently available. Returns true if invoked from
219/// inside of a procedural macro, false if invoked from any other binary.
220#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
221pub fn is_available() -> bool {
222 bridge::client::is_available()
223}
224225/// The main type provided by this crate, representing an abstract stream of
226/// tokens, or, more specifically, a sequence of token trees.
227/// The type provides interfaces for iterating over those token trees and, conversely,
228/// collecting a number of token trees into one stream.
229///
230/// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
231/// and `#[proc_macro_derive]` definitions.
232#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
233#[stable(feature = "proc_macro_lib", since = "1.15.0")]
234#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib", since = "1.15.0")]
impl ::core::clone::Clone for TokenStream {
#[inline]
fn clone(&self) -> Self { Self(::core::clone::Clone::clone(&self.0)) }
}Clone)]
235pub struct TokenStream(Option<bridge::client::TokenStream>);
236237#[stable(feature = "proc_macro_lib", since = "1.15.0")]
238impl !Sendfor TokenStream {}
239#[stable(feature = "proc_macro_lib", since = "1.15.0")]
240impl !Syncfor TokenStream {}
241242/// Error returned from `TokenStream::from_str`.
243///
244/// The contained error message is explicitly not guaranteed to be stable in any way,
245/// and may change between Rust versions or across compilations.
246#[stable(feature = "proc_macro_lib", since = "1.15.0")]
247#[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)]
248pub struct LexError(String);
249250#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
251impl fmt::Displayfor LexError {
252fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253f.write_str(&self.0)
254 }
255}
256257#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
258impl error::Errorfor LexError {}
259260#[stable(feature = "proc_macro_lib", since = "1.15.0")]
261impl !Sendfor LexError {}
262#[stable(feature = "proc_macro_lib", since = "1.15.0")]
263impl !Syncfor LexError {}
264265/// Error returned from `TokenStream::expand_expr`.
266#[unstable(feature = "proc_macro_expand", issue = "90765")]
267#[non_exhaustive]
268#[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)]
269pub struct ExpandError;
270271#[unstable(feature = "proc_macro_expand", issue = "90765")]
272impl fmt::Displayfor ExpandError {
273fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274f.write_str("macro expansion failed")
275 }
276}
277278#[unstable(feature = "proc_macro_expand", issue = "90765")]
279impl error::Errorfor ExpandError {}
280281#[unstable(feature = "proc_macro_expand", issue = "90765")]
282impl !Sendfor ExpandError {}
283284#[unstable(feature = "proc_macro_expand", issue = "90765")]
285impl !Syncfor ExpandError {}
286287impl TokenStream {
288/// Returns an empty `TokenStream` containing no token trees.
289#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
290pub fn new() -> TokenStream {
291TokenStream(None)
292 }
293294/// Checks if this `TokenStream` is empty.
295#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
296pub fn is_empty(&self) -> bool {
297self.0.as_ref().map(BridgeMethods::ts_is_empty).unwrap_or(true)
298 }
299300/// Parses this `TokenStream` as an expression and attempts to expand any
301 /// macros within it. Returns the expanded `TokenStream`.
302 ///
303 /// Currently only expressions expanding to literals will succeed, although
304 /// this may be relaxed in the future.
305 ///
306 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
307 /// report an error, failing compilation, and/or return an `Err(..)`. The
308 /// specific behavior for any error condition, and what conditions are
309 /// considered errors, is unspecified and may change in the future.
310#[unstable(feature = "proc_macro_expand", issue = "90765")]
311pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
312let stream = self.0.as_ref().ok_or(ExpandError)?;
313match BridgeMethods::ts_expand_expr(stream) {
314Ok(stream) => Ok(TokenStream(Some(stream))),
315Err(_) => Err(ExpandError),
316 }
317 }
318}
319320/// Attempts to break the string into tokens and parse those tokens into a token stream.
321/// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
322/// or characters not existing in the language.
323/// All tokens in the parsed stream get `Span::call_site()` spans.
324///
325/// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
326/// change these errors into `LexError`s later.
327#[stable(feature = "proc_macro_lib", since = "1.15.0")]
328impl FromStrfor TokenStream {
329type Err = LexError;
330331fn from_str(src: &str) -> Result<TokenStream, LexError> {
332Ok(TokenStream(Some(BridgeMethods::ts_from_str(src).map_err(LexError)?)))
333 }
334}
335336/// Prints the token stream as a string that is supposed to be losslessly convertible back
337/// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
338/// with `Delimiter::None` delimiters and negative numeric literals.
339///
340/// Note: the exact form of the output is subject to change, e.g. there might
341/// be changes in the whitespace used between tokens. Therefore, you should
342/// *not* do any kind of simple substring matching on the output string (as
343/// produced by `to_string`) to implement a proc macro, because that matching
344/// might stop working if such changes happen. Instead, you should work at the
345/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
346/// `TokenTree::Punct`, or `TokenTree::Literal`.
347#[stable(feature = "proc_macro_lib", since = "1.15.0")]
348impl fmt::Displayfor TokenStream {
349fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350match &self.0 {
351Some(ts) => f.write_fmt(format_args!("{0}", BridgeMethods::ts_to_string(ts)))write!(f, "{}", BridgeMethods::ts_to_string(ts)),
352None => Ok(()),
353 }
354 }
355}
356357/// Prints tokens in a form convenient for debugging.
358#[stable(feature = "proc_macro_lib", since = "1.15.0")]
359impl fmt::Debugfor TokenStream {
360fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 f.write_str("TokenStream ")?;
362f.debug_list().entries(self.clone()).finish()
363 }
364}
365366#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
367impl Defaultfor TokenStream {
368fn default() -> Self {
369TokenStream::new()
370 }
371}
372373#[unstable(feature = "proc_macro_quote", issue = "54722")]
374pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
375376fn tree_to_bridge_tree(
377 tree: TokenTree,
378) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
379match tree {
380 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
381 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
382 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
383 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
384 }
385}
386387/// Creates a token stream containing a single token tree.
388#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
389impl From<TokenTree> for TokenStream {
390fn from(tree: TokenTree) -> TokenStream {
391TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
392 }
393}
394395/// Non-generic helper for implementing `FromIterator<TokenTree>` and
396/// `Extend<TokenTree>` with less monomorphization in calling crates.
397struct ConcatTreesHelper {
398 trees: Vec<
399 bridge::TokenTree<
400 bridge::client::TokenStream,
401 bridge::client::Span,
402 bridge::client::Symbol,
403 >,
404 >,
405}
406407impl ConcatTreesHelper {
408fn new(capacity: usize) -> Self {
409ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
410 }
411412fn push(&mut self, tree: TokenTree) {
413self.trees.push(tree_to_bridge_tree(tree));
414 }
415416fn build(self) -> TokenStream {
417if self.trees.is_empty() {
418TokenStream(None)
419 } else {
420TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
421 }
422 }
423424fn append_to(self, stream: &mut TokenStream) {
425if self.trees.is_empty() {
426return;
427 }
428stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
429 }
430}
431432/// Non-generic helper for implementing `FromIterator<TokenStream>` and
433/// `Extend<TokenStream>` with less monomorphization in calling crates.
434struct ConcatStreamsHelper {
435 streams: Vec<bridge::client::TokenStream>,
436}
437438impl ConcatStreamsHelper {
439fn new(capacity: usize) -> Self {
440ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
441 }
442443fn push(&mut self, stream: TokenStream) {
444if let Some(stream) = stream.0 {
445self.streams.push(stream);
446 }
447 }
448449fn build(mut self) -> TokenStream {
450if self.streams.len() <= 1 {
451TokenStream(self.streams.pop())
452 } else {
453TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
454 }
455 }
456457fn append_to(mut self, stream: &mut TokenStream) {
458if self.streams.is_empty() {
459return;
460 }
461let base = stream.0.take();
462if base.is_none() && self.streams.len() == 1 {
463stream.0 = self.streams.pop();
464 } else {
465stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
466 }
467 }
468}
469470/// Collects a number of token trees into a single stream.
471#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
472impl FromIterator<TokenTree> for TokenStream {
473fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
474let iter = trees.into_iter();
475let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
476iter.for_each(|tree| builder.push(tree));
477builder.build()
478 }
479}
480481/// A "flattening" operation on token streams, collects token trees
482/// from multiple token streams into a single stream.
483#[stable(feature = "proc_macro_lib", since = "1.15.0")]
484impl FromIterator<TokenStream> for TokenStream {
485fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
486let iter = streams.into_iter();
487let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
488iter.for_each(|stream| builder.push(stream));
489builder.build()
490 }
491}
492493#[stable(feature = "token_stream_extend", since = "1.30.0")]
494impl Extend<TokenTree> for TokenStream {
495fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
496let iter = trees.into_iter();
497let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
498iter.for_each(|tree| builder.push(tree));
499builder.append_to(self);
500 }
501}
502503#[stable(feature = "token_stream_extend", since = "1.30.0")]
504impl Extend<TokenStream> for TokenStream {
505fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
506let iter = streams.into_iter();
507let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
508iter.for_each(|stream| builder.push(stream));
509builder.append_to(self);
510 }
511}
512513macro_rules!extend_items {
514 ($($item:ident)*) => {
515 $(
516#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
517impl Extend<$item> for TokenStream {
518fn extend<I: IntoIterator<Item = $item>>(&mut self, iter: I) {
519self.extend(iter.into_iter().map(TokenTree::$item));
520 }
521 }
522 )*
523 };
524}
525526#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Group> for TokenStream {
fn extend<I: IntoIterator<Item = Group>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(TokenTree::Group));
}
}
#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Literal> for TokenStream {
fn extend<I: IntoIterator<Item = Literal>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(TokenTree::Literal));
}
}
#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Punct> for TokenStream {
fn extend<I: IntoIterator<Item = Punct>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(TokenTree::Punct));
}
}
#[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
impl Extend<Ident> for TokenStream {
fn extend<I: IntoIterator<Item = Ident>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(TokenTree::Ident));
}
}extend_items!(Group Literal Punct Ident);
527528/// Public implementation details for the `TokenStream` type, such as iterators.
529#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
530pub mod token_stream {
531use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
532533/// An iterator over `TokenStream`'s `TokenTree`s.
534 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
535 /// and returns whole groups as token trees.
536#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for IntoIter {
#[inline]
fn clone(&self) -> Self { Self(::core::clone::Clone::clone(&self.0)) }
}Clone)]
537 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
538pub struct IntoIter(
539 std::vec::IntoIter<
540 bridge::TokenTree<
541 bridge::client::TokenStream,
542 bridge::client::Span,
543 bridge::client::Symbol,
544 >,
545 >,
546 );
547548#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
549impl Iteratorfor IntoIter {
550type Item = TokenTree;
551552fn next(&mut self) -> Option<TokenTree> {
553self.0.next().map(|tree| match tree {
554 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
555 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
556 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
557 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
558 })
559 }
560561fn size_hint(&self) -> (usize, Option<usize>) {
562self.0.size_hint()
563 }
564565fn count(self) -> usize {
566self.0.count()
567 }
568 }
569570#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
571impl IntoIteratorfor TokenStream {
572type Item = TokenTree;
573type IntoIter = IntoIter;
574575fn into_iter(self) -> IntoIter {
576IntoIter(self.0.map(BridgeMethods::ts_into_trees).unwrap_or_default().into_iter())
577 }
578 }
579}
580581/// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
582/// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
583/// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
584///
585/// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
586/// To quote `$` itself, use `$$`.
587#[unstable(feature = "proc_macro_quote", issue = "54722")]
588#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
589#[rustc_builtin_macro]
590pub macro quote($($t:tt)*) {
591/* compiler built-in */
592}
593594#[unstable(feature = "proc_macro_internals", issue = "none")]
595#[doc(hidden)]
596mod quote;
597598/// A region of source code, along with macro expansion information.
599#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
600#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Span { }Copy, #[automatically_derived]
#[doc(hidden)]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
unsafe impl ::core::clone::TrivialClone for Span { }
#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Span {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<bridge::client::Span>;
*self
}
}Clone)]
601pub struct Span(bridge::client::Span);
602603#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
604impl !Sendfor Span {}
605#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
606impl !Syncfor Span {}
607608macro_rules!diagnostic_method {
609 ($name:ident, $level:expr) => {
610/// Creates a new `Diagnostic` with the given `message` at the span
611 /// `self`.
612#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
613pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
614 Diagnostic::spanned(self, $level, message)
615 }
616 };
617}
618619impl Span {
620/// A span that resolves at the macro definition site.
621#[unstable(feature = "proc_macro_def_site", issue = "54724")]
622pub fn def_site() -> Span {
623Span(bridge::client::Span::def_site())
624 }
625626/// The span of the invocation of the current procedural macro.
627 /// Identifiers created with this span will be resolved as if they were written
628 /// directly at the macro call location (call-site hygiene) and other code
629 /// at the macro call site will be able to refer to them as well.
630#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
631pub fn call_site() -> Span {
632Span(bridge::client::Span::call_site())
633 }
634635/// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
636 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
637 /// call site (everything else).
638 /// The span location is taken from the call-site.
639#[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
640pub fn mixed_site() -> Span {
641Span(bridge::client::Span::mixed_site())
642 }
643644/// The `Span` for the tokens in the previous macro expansion from which
645 /// `self` was generated from, if any.
646#[unstable(feature = "proc_macro_span", issue = "54725")]
647pub fn parent(&self) -> Option<Span> {
648BridgeMethods::span_parent(self.0).map(Span)
649 }
650651/// The span for the origin source code that `self` was generated from. If
652 /// this `Span` wasn't generated from other macro expansions then the return
653 /// value is the same as `*self`.
654#[unstable(feature = "proc_macro_span", issue = "54725")]
655pub fn source(&self) -> Span {
656Span(BridgeMethods::span_source(self.0))
657 }
658659/// Returns the span's byte position range in the source file.
660#[unstable(feature = "proc_macro_span", issue = "54725")]
661pub fn byte_range(&self) -> Range<usize> {
662BridgeMethods::span_byte_range(self.0)
663 }
664665/// Creates an empty span pointing to directly before this span.
666#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
667pub fn start(&self) -> Span {
668Span(BridgeMethods::span_start(self.0))
669 }
670671/// Creates an empty span pointing to directly after this span.
672#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
673pub fn end(&self) -> Span {
674Span(BridgeMethods::span_end(self.0))
675 }
676677/// The one-indexed line of the source file where the span starts.
678 ///
679 /// To obtain the line of the span's end, use `span.end().line()`.
680#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
681pub fn line(&self) -> usize {
682BridgeMethods::span_line(self.0)
683 }
684685/// The one-indexed column of the source file where the span starts.
686 ///
687 /// To obtain the column of the span's end, use `span.end().column()`.
688#[stable(feature = "proc_macro_span_location", since = "1.88.0")]
689pub fn column(&self) -> usize {
690BridgeMethods::span_column(self.0)
691 }
692693/// The path to the source file in which this span occurs, for display purposes.
694 ///
695 /// This might not correspond to a valid file system path.
696 /// It might be remapped (e.g. `"/src/lib.rs"`) or an artificial path (e.g. `"<command line>"`).
697#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
698pub fn file(&self) -> String {
699BridgeMethods::span_file(self.0)
700 }
701702/// The path to the source file in which this span occurs on the local file system.
703 ///
704 /// This is the actual path on disk. It is unaffected by path remapping.
705 ///
706 /// This path should not be embedded in the output of the macro; prefer `file()` instead.
707#[stable(feature = "proc_macro_span_file", since = "1.88.0")]
708pub fn local_file(&self) -> Option<PathBuf> {
709BridgeMethods::span_local_file(self.0).map(PathBuf::from)
710 }
711712/// Creates a new span encompassing `self` and `other`.
713 ///
714 /// Returns `None` if `self` and `other` are from different files.
715#[unstable(feature = "proc_macro_span", issue = "54725")]
716pub fn join(&self, other: Span) -> Option<Span> {
717BridgeMethods::span_join(self.0, other.0).map(Span)
718 }
719720/// Creates a new span with the same line/column information as `self` but
721 /// that resolves symbols as though it were at `other`.
722#[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
723pub fn resolved_at(&self, other: Span) -> Span {
724Span(BridgeMethods::span_resolved_at(self.0, other.0))
725 }
726727/// Creates a new span with the same name resolution behavior as `self` but
728 /// with the line/column information of `other`.
729#[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
730pub fn located_at(&self, other: Span) -> Span {
731other.resolved_at(*self)
732 }
733734/// Compares two spans to see if they're equal.
735#[unstable(feature = "proc_macro_span", issue = "54725")]
736pub fn eq(&self, other: &Span) -> bool {
737self.0 == other.0
738}
739740/// Returns the source text behind a span. This preserves the original source
741 /// code, including spaces and comments. It only returns a result if the span
742 /// corresponds to real source code.
743 ///
744 /// Note: The observable result of a macro should only rely on the tokens and
745 /// not on this source text. The result of this function is a best effort to
746 /// be used for diagnostics only.
747#[stable(feature = "proc_macro_source_text", since = "1.66.0")]
748pub fn source_text(&self) -> Option<String> {
749BridgeMethods::span_source_text(self.0)
750 }
751752// Used by the implementation of `Span::quote`
753#[doc(hidden)]
754 #[unstable(feature = "proc_macro_internals", issue = "none")]
755pub fn save_span(&self) -> usize {
756BridgeMethods::span_save_span(self.0)
757 }
758759// Used by the implementation of `Span::quote`
760#[doc(hidden)]
761 #[unstable(feature = "proc_macro_internals", issue = "none")]
762pub fn recover_proc_macro_span(id: usize) -> Span {
763Span(BridgeMethods::span_recover_proc_macro_span(id))
764 }
765766/// 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);
767/// 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);
768/// 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);
769/// 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);
770}
771772/// Prints a span in a form convenient for debugging.
773#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
774impl fmt::Debugfor Span {
775fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
776self.0.fmt(f)
777 }
778}
779780/// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
781#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
782#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for TokenTree {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Group(__self_0) =>
Self::Group(::core::clone::Clone::clone(__self_0)),
Self::Ident(__self_0) =>
Self::Ident(::core::clone::Clone::clone(__self_0)),
Self::Punct(__self_0) =>
Self::Punct(::core::clone::Clone::clone(__self_0)),
Self::Literal(__self_0) =>
Self::Literal(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
783pub enum TokenTree {
784/// A token stream surrounded by bracket delimiters.
785#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
787/// An identifier.
788#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
790/// A single punctuation character (`+`, `,`, `$`, etc.).
791#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
792Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
793/// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
794#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
795Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
796}
797798#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
799impl !Sendfor TokenTree {}
800#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
801impl !Syncfor TokenTree {}
802803impl TokenTree {
804/// Returns the span of this tree, delegating to the `span` method of
805 /// the contained token or a delimited stream.
806#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
807pub fn span(&self) -> Span {
808match *self {
809 TokenTree::Group(ref t) => t.span(),
810 TokenTree::Ident(ref t) => t.span(),
811 TokenTree::Punct(ref t) => t.span(),
812 TokenTree::Literal(ref t) => t.span(),
813 }
814 }
815816/// Configures the span for *only this token*.
817 ///
818 /// Note that if this token is a `Group` then this method will not configure
819 /// the span of each of the internal tokens, this will simply delegate to
820 /// the `set_span` method of each variant.
821#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
822pub fn set_span(&mut self, span: Span) {
823match *self {
824 TokenTree::Group(ref mut t) => t.set_span(span),
825 TokenTree::Ident(ref mut t) => t.set_span(span),
826 TokenTree::Punct(ref mut t) => t.set_span(span),
827 TokenTree::Literal(ref mut t) => t.set_span(span),
828 }
829 }
830}
831832/// Prints token tree in a form convenient for debugging.
833#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
834impl fmt::Debugfor TokenTree {
835fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
836// Each of these has the name in the struct type in the derived debug,
837 // so don't bother with an extra layer of indirection
838match *self {
839 TokenTree::Group(ref tt) => tt.fmt(f),
840 TokenTree::Ident(ref tt) => tt.fmt(f),
841 TokenTree::Punct(ref tt) => tt.fmt(f),
842 TokenTree::Literal(ref tt) => tt.fmt(f),
843 }
844 }
845}
846847#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
848impl From<Group> for TokenTree {
849fn from(g: Group) -> TokenTree {
850 TokenTree::Group(g)
851 }
852}
853854#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
855impl From<Ident> for TokenTree {
856fn from(g: Ident) -> TokenTree {
857 TokenTree::Ident(g)
858 }
859}
860861#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
862impl From<Punct> for TokenTree {
863fn from(g: Punct) -> TokenTree {
864 TokenTree::Punct(g)
865 }
866}
867868#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
869impl From<Literal> for TokenTree {
870fn from(g: Literal) -> TokenTree {
871 TokenTree::Literal(g)
872 }
873}
874875/// Prints the token tree as a string that is supposed to be losslessly convertible back
876/// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
877/// with `Delimiter::None` delimiters and negative numeric literals.
878///
879/// Note: the exact form of the output is subject to change, e.g. there might
880/// be changes in the whitespace used between tokens. Therefore, you should
881/// *not* do any kind of simple substring matching on the output string (as
882/// produced by `to_string`) to implement a proc macro, because that matching
883/// might stop working if such changes happen. Instead, you should work at the
884/// `TokenTree` level, e.g. matching against `TokenTree::Ident`,
885/// `TokenTree::Punct`, or `TokenTree::Literal`.
886#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
887impl fmt::Displayfor TokenTree {
888fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
889match self {
890 TokenTree::Group(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
891 TokenTree::Ident(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
892 TokenTree::Punct(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
893 TokenTree::Literal(t) => f.write_fmt(format_args!("{0}", t))write!(f, "{t}"),
894 }
895 }
896}
897898/// A delimited token stream.
899///
900/// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
901#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Group {
#[inline]
fn clone(&self) -> Self { Self(::core::clone::Clone::clone(&self.0)) }
}Clone)]
902#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
903pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
904905#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
906impl !Sendfor Group {}
907#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
908impl !Syncfor Group {}
909910/// Describes how a sequence of token trees is delimited.
911#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Delimiter { }Copy, #[automatically_derived]
#[doc(hidden)]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
unsafe impl ::core::clone::TrivialClone for Delimiter { }
#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Delimiter {
#[inline]
fn clone(&self) -> Self { *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::marker::StructuralPartialEq for Delimiter { }
#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::PartialEq for Delimiter {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::Eq for Delimiter { }Eq)]
912#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
913pub enum Delimiter {
914/// `( ... )`
915#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
916Parenthesis,
917/// `{ ... }`
918#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
919Brace,
920/// `[ ... ]`
921#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
922Bracket,
923/// `∅ ... ∅`
924 /// An invisible delimiter, that may, for example, appear around tokens coming from a
925 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
926 /// `$var * 3` where `$var` is `1 + 2`.
927 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
928 ///
929 /// <div class="warning">
930 ///
931 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output
932 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input
933 /// of a proc_macro macro are preserved, and only in very specific circumstances.
934 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve
935 /// operator priorities as indicated above. The other `Delimiter` variants should be used
936 /// instead in this context. This is a rustc bug. For details, see
937 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062).
938 ///
939 /// </div>
940#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
941None,
942}
943944impl Group {
945/// Creates a new `Group` with the given delimiter and token stream.
946 ///
947 /// This constructor will set the span for this group to
948 /// `Span::call_site()`. To change the span you can use the `set_span`
949 /// method below.
950#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
951pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
952Group(bridge::Group {
953delimiter,
954 stream: stream.0,
955 span: bridge::DelimSpan::from_single(Span::call_site().0),
956 })
957 }
958959/// Returns the delimiter of this `Group`
960#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
961pub fn delimiter(&self) -> Delimiter {
962self.0.delimiter
963 }
964965/// Returns the `TokenStream` of tokens that are delimited in this `Group`.
966 ///
967 /// Note that the returned token stream does not include the delimiter
968 /// returned above.
969#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
970pub fn stream(&self) -> TokenStream {
971TokenStream(self.0.stream.clone())
972 }
973974/// Returns the span for the delimiters of this token stream, spanning the
975 /// entire `Group`.
976 ///
977 /// ```text
978 /// pub fn span(&self) -> Span {
979 /// ^^^^^^^
980 /// ```
981#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
982pub fn span(&self) -> Span {
983Span(self.0.span.entire)
984 }
985986/// Returns the span pointing to the opening delimiter of this group.
987 ///
988 /// ```text
989 /// pub fn span_open(&self) -> Span {
990 /// ^
991 /// ```
992#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
993pub fn span_open(&self) -> Span {
994Span(self.0.span.open)
995 }
996997/// Returns the span pointing to the closing delimiter of this group.
998 ///
999 /// ```text
1000 /// pub fn span_close(&self) -> Span {
1001 /// ^
1002 /// ```
1003#[stable(feature = "proc_macro_group_span", since = "1.55.0")]
1004pub fn span_close(&self) -> Span {
1005Span(self.0.span.close)
1006 }
10071008/// Configures the span for this `Group`'s delimiters, but not its internal
1009 /// tokens.
1010 ///
1011 /// This method will **not** set the span of all the internal tokens spanned
1012 /// by this group, but rather it will only set the span of the delimiter
1013 /// tokens at the level of the `Group`.
1014#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1015pub fn set_span(&mut self, span: Span) {
1016self.0.span = bridge::DelimSpan::from_single(span.0);
1017 }
1018}
10191020/// Prints the group as a string that should be losslessly convertible back
1021/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
1022/// with `Delimiter::None` delimiters.
1023#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1024impl fmt::Displayfor Group {
1025fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1026f.write_fmt(format_args!("{0}",
TokenStream::from(TokenTree::from(self.clone()))))write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))1027 }
1028}
10291030#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1031impl fmt::Debugfor Group {
1032fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1033f.debug_struct("Group")
1034 .field("delimiter", &self.delimiter())
1035 .field("stream", &self.stream())
1036 .field("span", &self.span())
1037 .finish()
1038 }
1039}
10401041/// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
1042///
1043/// Multi-character operators like `+=` are represented as two instances of `Punct` with different
1044/// forms of `Spacing` returned.
1045#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1046#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Punct {
#[inline]
fn clone(&self) -> Self { Self(::core::clone::Clone::clone(&self.0)) }
}Clone)]
1047pub struct Punct(bridge::Punct<bridge::client::Span>);
10481049#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1050impl !Sendfor Punct {}
1051#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1052impl !Syncfor Punct {}
10531054/// Indicates whether a `Punct` token can join with the following token
1055/// to form a multi-character operator.
1056#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::marker::Copy for Spacing { }Copy, #[automatically_derived]
#[doc(hidden)]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
unsafe impl ::core::clone::TrivialClone for Spacing { }
#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Spacing {
#[inline]
fn clone(&self) -> Self { *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::marker::StructuralPartialEq for Spacing { }
#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::PartialEq for Spacing {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::cmp::Eq for Spacing { }Eq)]
1057#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1058pub enum Spacing {
1059/// A `Punct` token can join with the following token to form a multi-character operator.
1060 ///
1061 /// In token streams constructed using proc macro interfaces, `Joint` punctuation tokens can be
1062 /// followed by any other tokens. However, in token streams parsed from source code, the
1063 /// compiler will only set spacing to `Joint` in the following cases.
1064 /// - When a `Punct` is immediately followed by another `Punct` without a whitespace. E.g. `+`
1065 /// is `Joint` in `+=` and `++`.
1066 /// - When a single quote `'` is immediately followed by an identifier without a whitespace.
1067 /// E.g. `'` is `Joint` in `'lifetime`.
1068 ///
1069 /// This list may be extended in the future to enable more token combinations.
1070#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1071Joint,
1072/// A `Punct` token cannot join with the following token to form a multi-character operator.
1073 ///
1074 /// `Alone` punctuation tokens can be followed by any other tokens. In token streams parsed
1075 /// from source code, the compiler will set spacing to `Alone` in all cases not covered by the
1076 /// conditions for `Joint` above. E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`. In
1077 /// particular, tokens not followed by anything will be marked as `Alone`.
1078#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1079Alone,
1080}
10811082impl Punct {
1083/// Creates a new `Punct` from the given character and spacing.
1084 /// The `ch` argument must be a valid punctuation character permitted by the language,
1085 /// otherwise the function will panic.
1086 ///
1087 /// The returned `Punct` will have the default span of `Span::call_site()`
1088 /// which can be further configured with the `set_span` method below.
1089#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1090pub fn new(ch: char, spacing: Spacing) -> Punct {
1091const LEGAL_CHARS: &[char] = &[
1092'=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
1093':', '#', '$', '?', '\'',
1094 ];
1095if !LEGAL_CHARS.contains(&ch) {
1096{
::core::panicking::panic_fmt(format_args!("unsupported character `{0:?}`",
ch));
};panic!("unsupported character `{:?}`", ch);
1097 }
1098Punct(bridge::Punct {
1099 ch: chas u8,
1100 joint: spacing == Spacing::Joint,
1101 span: Span::call_site().0,
1102 })
1103 }
11041105/// Returns the value of this punctuation character as `char`.
1106#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1107pub fn as_char(&self) -> char {
1108self.0.ch as char1109 }
11101111/// Returns the spacing of this punctuation character, indicating whether it can be potentially
1112 /// combined into a multi-character operator with the following token (`Joint`), or whether the
1113 /// operator has definitely ended (`Alone`).
1114#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1115pub fn spacing(&self) -> Spacing {
1116if self.0.joint { Spacing::Joint } else { Spacing::Alone }
1117 }
11181119/// Returns the span for this punctuation character.
1120#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1121pub fn span(&self) -> Span {
1122Span(self.0.span)
1123 }
11241125/// Configure the span for this punctuation character.
1126#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1127pub fn set_span(&mut self, span: Span) {
1128self.0.span = span.0;
1129 }
1130}
11311132/// Prints the punctuation character as a string that should be losslessly convertible
1133/// back into the same character.
1134#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1135impl fmt::Displayfor Punct {
1136fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1137f.write_fmt(format_args!("{0}", self.as_char()))write!(f, "{}", self.as_char())1138 }
1139}
11401141#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1142impl fmt::Debugfor Punct {
1143fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1144f.debug_struct("Punct")
1145 .field("ch", &self.as_char())
1146 .field("spacing", &self.spacing())
1147 .field("span", &self.span())
1148 .finish()
1149 }
1150}
11511152#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1153impl PartialEq<char> for Punct {
1154fn eq(&self, rhs: &char) -> bool {
1155self.as_char() == *rhs1156 }
1157}
11581159#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1160impl PartialEq<Punct> for char {
1161fn eq(&self, rhs: &Punct) -> bool {
1162*self == rhs.as_char()
1163 }
1164}
11651166/// An identifier (`ident`).
1167#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Ident {
#[inline]
fn clone(&self) -> Self { Self(::core::clone::Clone::clone(&self.0)) }
}Clone)]
1168#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1169pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
11701171impl Ident {
1172/// Creates a new `Ident` with the given `string` as well as the specified
1173 /// `span`.
1174 /// The `string` argument must be a valid identifier permitted by the
1175 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
1176 ///
1177 /// The constructed identifier will be NFC-normalized. See the [Reference] for more info.
1178 ///
1179 /// Note that `span`, currently in rustc, configures the hygiene information
1180 /// for this identifier.
1181 ///
1182 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
1183 /// meaning that identifiers created with this span will be resolved as if they were written
1184 /// directly at the location of the macro call, and other code at the macro call site will be
1185 /// able to refer to them as well.
1186 ///
1187 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
1188 /// meaning that identifiers created with this span will be resolved at the location of the
1189 /// macro definition and other code at the macro call site will not be able to refer to them.
1190 ///
1191 /// Due to the current importance of hygiene this constructor, unlike other
1192 /// tokens, requires a `Span` to be specified at construction.
1193 ///
1194 /// [Reference]: https://doc.rust-lang.org/nightly/reference/identifiers.html#r-ident.normalization
1195#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1196pub fn new(string: &str, span: Span) -> Ident {
1197Ident(bridge::Ident {
1198 sym: bridge::client::Symbol::new_ident(string, false),
1199 kind: bridge::IdentKind::Normal,
1200 span: span.0,
1201 })
1202 }
12031204/// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
1205 /// The `string` argument be a valid identifier permitted by the language
1206 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
1207 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
1208#[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1209pub fn new_raw(string: &str, span: Span) -> Ident {
1210Ident(bridge::Ident {
1211 sym: bridge::client::Symbol::new_ident(string, true),
1212 kind: bridge::IdentKind::Raw,
1213 span: span.0,
1214 })
1215 }
12161217/// Returns the span of this `Ident`, encompassing the entire string returned
1218 /// by [`to_string`](ToString::to_string).
1219#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1220pub fn span(&self) -> Span {
1221Span(self.0.span)
1222 }
12231224/// Configures the span of this `Ident`, possibly changing its hygiene context.
1225#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1226pub fn set_span(&mut self, span: Span) {
1227self.0.span = span.0;
1228 }
1229}
12301231/// Prints the identifier as a string that should be losslessly convertible back
1232/// into the same identifier.
1233#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1234impl fmt::Displayfor Ident {
1235fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1236if let Some(prefix) = self.0.kind.prefix() {
1237 f.write_str(prefix)?;
1238 }
1239 fmt::Display::fmt(&self.0.sym, f)
1240 }
1241}
12421243#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1244impl fmt::Debugfor Ident {
1245fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1246f.debug_struct("Ident")
1247 .field("ident", &self.to_string())
1248 .field("span", &self.span())
1249 .finish()
1250 }
1251}
12521253/// A literal string (`"hello"`), byte string (`b"hello"`), C string (`c"hello"`),
1254/// character (`'a'`), byte character (`b'a'`), an integer or floating point number
1255/// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
1256/// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
1257#[derive(#[automatically_derived]
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
impl ::core::clone::Clone for Literal {
#[inline]
fn clone(&self) -> Self { Self(::core::clone::Clone::clone(&self.0)) }
}Clone)]
1258#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1259pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
12601261macro_rules!suffixed_int_literals {
1262 ($($name:ident => $kind:ident,)*) => ($(
1263/// Creates a new suffixed integer literal with the specified value.
1264 ///
1265 /// This function will create an integer like `1u32` where the integer
1266 /// value specified is the first part of the token and the integral is
1267 /// also suffixed at the end.
1268 /// Literals created from negative numbers might not survive round-trips through
1269 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1270 ///
1271 /// Literals created through this method have the `Span::call_site()`
1272 /// span by default, which can be configured with the `set_span` method
1273 /// below.
1274#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1275pub fn $name(n: $kind) -> Literal {
1276 Literal(bridge::Literal {
1277 kind: bridge::LitKind::Integer,
1278 symbol: bridge::client::Symbol::new(&n.to_string()),
1279 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1280 span: Span::call_site().0,
1281 })
1282 }
1283 )*)
1284}
12851286macro_rules!unsuffixed_int_literals {
1287 ($($name:ident => $kind:ident,)*) => ($(
1288/// Creates a new unsuffixed integer literal with the specified value.
1289 ///
1290 /// This function will create an integer like `1` where the integer
1291 /// value specified is the first part of the token. No suffix is
1292 /// specified on this token, meaning that invocations like
1293 /// `Literal::i8_unsuffixed(1)` are equivalent to
1294 /// `Literal::u32_unsuffixed(1)`.
1295 /// Literals created from negative numbers might not survive roundtrips through
1296 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1297 ///
1298 /// Literals created through this method have the `Span::call_site()`
1299 /// span by default, which can be configured with the `set_span` method
1300 /// below.
1301#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1302pub fn $name(n: $kind) -> Literal {
1303 Literal(bridge::Literal {
1304 kind: bridge::LitKind::Integer,
1305 symbol: bridge::client::Symbol::new(&n.to_string()),
1306 suffix: None,
1307 span: Span::call_site().0,
1308 })
1309 }
1310 )*)
1311}
13121313macro_rules!integer_values {
1314 ($($nb:ident => $fn_name:ident,)+) => {
1315 $(
1316#[doc = concat!(
1317"Returns the unescaped `",
1318stringify!($nb),
1319"` value if the literal is a `",
1320stringify!($nb),
1321"` or if it's an \"unmarked\" integer which doesn't overflow.")]
1322 #[unstable(feature = "proc_macro_value", issue = "136652")]
1323pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1324if self.0.kind != bridge::LitKind::Integer {
1325return Err(ConversionErrorKind::InvalidLiteralKind);
1326 }
1327self.with_symbol_and_suffix(|symbol, suffix| {
1328match suffix {
1329stringify!($nb) | "" => {
1330let symbol = strip_underscores(symbol);
1331let (number, base) = parse_number(&symbol);
1332$nb::from_str_radix(&number, base as u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1333 }
1334_ => Err(ConversionErrorKind::InvalidLiteralKind),
1335 }
1336 })
1337 }
1338 )+
1339 }
1340}
13411342macro_rules!float_values {
1343 ($($nb:ident => $fn_name:ident,)+) => {
1344 $(
1345#[doc = concat!(
1346"Returns the unescaped `",
1347stringify!($nb),
1348"` value if the literal is a `",
1349stringify!($nb),
1350"` or if it's an \"unmarked\" float which doesn't overflow.")]
1351 #[unstable(feature = "proc_macro_value", issue = "136652")]
1352pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1353if self.0.kind != bridge::LitKind::Float {
1354return Err(ConversionErrorKind::InvalidLiteralKind);
1355 }
1356self.with_symbol_and_suffix(|symbol, suffix| {
1357match suffix {
1358stringify!($nb) | "" => {
1359let number = strip_underscores(symbol);
1360$nb::from_str(&number).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1361 }
1362_ => Err(ConversionErrorKind::InvalidLiteralKind),
1363 }
1364 })
1365 }
1366 )+
1367 }
1368}
13691370impl Literal {
1371fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1372Literal(bridge::Literal {
1373kind,
1374 symbol: bridge::client::Symbol::new(value),
1375 suffix: suffix.map(bridge::client::Symbol::new),
1376 span: Span::call_site().0,
1377 })
1378 }
13791380/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u8_suffixed(n: u8) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("u8")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u16_suffixed(n: u16) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("u16")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u32_suffixed(n: u32) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("u32")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u64_suffixed(n: u64) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("u64")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u128_suffixed(n: u128) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("u128")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn usize_suffixed(n: usize) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("usize")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i8_suffixed(n: i8) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("i8")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i16_suffixed(n: i16) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("i16")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i32_suffixed(n: i32) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("i32")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i64_suffixed(n: i64) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("i64")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i128_suffixed(n: i128) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("i128")),
span: Span::call_site().0,
})
}
/// Creates a new suffixed integer literal with the specified value.
///
/// This function will create an integer like `1u32` where the integer
/// value specified is the first part of the token and the integral is
/// also suffixed at the end.
/// Literals created from negative numbers might not survive round-trips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn isize_suffixed(n: isize) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: Some(bridge::client::Symbol::new("isize")),
span: Span::call_site().0,
})
}suffixed_int_literals! {
1381 u8_suffixed => u8,
1382 u16_suffixed => u16,
1383 u32_suffixed => u32,
1384 u64_suffixed => u64,
1385 u128_suffixed => u128,
1386 usize_suffixed => usize,
1387 i8_suffixed => i8,
1388 i16_suffixed => i16,
1389 i32_suffixed => i32,
1390 i64_suffixed => i64,
1391 i128_suffixed => i128,
1392 isize_suffixed => isize,
1393 }13941395/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u8_unsuffixed(n: u8) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u16_unsuffixed(n: u16) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u32_unsuffixed(n: u32) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u64_unsuffixed(n: u64) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn u128_unsuffixed(n: u128) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn usize_unsuffixed(n: usize) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i8_unsuffixed(n: i8) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i16_unsuffixed(n: i16) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i32_unsuffixed(n: i32) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i64_unsuffixed(n: i64) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn i128_unsuffixed(n: i128) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}
/// Creates a new unsuffixed integer literal with the specified value.
///
/// This function will create an integer like `1` where the integer
/// value specified is the first part of the token. No suffix is
/// specified on this token, meaning that invocations like
/// `Literal::i8_unsuffixed(1)` are equivalent to
/// `Literal::u32_unsuffixed(1)`.
/// Literals created from negative numbers might not survive roundtrips through
/// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
///
/// Literals created through this method have the `Span::call_site()`
/// span by default, which can be configured with the `set_span` method
/// below.
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn isize_unsuffixed(n: isize) -> Literal {
Literal(bridge::Literal {
kind: bridge::LitKind::Integer,
symbol: bridge::client::Symbol::new(&n.to_string()),
suffix: None,
span: Span::call_site().0,
})
}unsuffixed_int_literals! {
1396 u8_unsuffixed => u8,
1397 u16_unsuffixed => u16,
1398 u32_unsuffixed => u32,
1399 u64_unsuffixed => u64,
1400 u128_unsuffixed => u128,
1401 usize_unsuffixed => usize,
1402 i8_unsuffixed => i8,
1403 i16_unsuffixed => i16,
1404 i32_unsuffixed => i32,
1405 i64_unsuffixed => i64,
1406 i128_unsuffixed => i128,
1407 isize_unsuffixed => isize,
1408 }14091410/// Creates a new unsuffixed floating-point literal.
1411 ///
1412 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1413 /// the float's value is emitted directly into the token but no suffix is
1414 /// used, so it may be inferred to be a `f64` later in the compiler.
1415 /// Literals created from negative numbers might not survive roundtrips through
1416 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1417 ///
1418 /// # Panics
1419 ///
1420 /// This function requires that the specified float is finite, for
1421 /// example if it is infinity or NaN this function will panic.
1422#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1423pub fn f32_unsuffixed(n: f32) -> Literal {
1424if !n.is_finite() {
1425{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1426 }
1427let mut repr = n.to_string();
1428if !repr.contains('.') {
1429repr.push_str(".0");
1430 }
1431Literal::new(bridge::LitKind::Float, &repr, None)
1432 }
14331434/// Creates a new suffixed floating-point literal.
1435 ///
1436 /// This constructor will create a literal like `1.0f32` where the value
1437 /// specified is the preceding part of the token and `f32` is the suffix of
1438 /// the token. This token will always be inferred to be an `f32` in the
1439 /// compiler.
1440 /// Literals created from negative numbers might not survive roundtrips through
1441 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1442 ///
1443 /// # Panics
1444 ///
1445 /// This function requires that the specified float is finite, for
1446 /// example if it is infinity or NaN this function will panic.
1447#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1448pub fn f32_suffixed(n: f32) -> Literal {
1449if !n.is_finite() {
1450{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1451 }
1452Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1453 }
14541455/// Creates a new unsuffixed floating-point literal.
1456 ///
1457 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1458 /// the float's value is emitted directly into the token but no suffix is
1459 /// used, so it may be inferred to be a `f64` later in the compiler.
1460 /// Literals created from negative numbers might not survive roundtrips through
1461 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1462 ///
1463 /// # Panics
1464 ///
1465 /// This function requires that the specified float is finite, for
1466 /// example if it is infinity or NaN this function will panic.
1467#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1468pub fn f64_unsuffixed(n: f64) -> Literal {
1469if !n.is_finite() {
1470{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1471 }
1472let mut repr = n.to_string();
1473if !repr.contains('.') {
1474repr.push_str(".0");
1475 }
1476Literal::new(bridge::LitKind::Float, &repr, None)
1477 }
14781479/// Creates a new suffixed floating-point literal.
1480 ///
1481 /// This constructor will create a literal like `1.0f64` where the value
1482 /// specified is the preceding part of the token and `f64` is the suffix of
1483 /// the token. This token will always be inferred to be an `f64` in the
1484 /// compiler.
1485 /// Literals created from negative numbers might not survive roundtrips through
1486 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1487 ///
1488 /// # Panics
1489 ///
1490 /// This function requires that the specified float is finite, for
1491 /// example if it is infinity or NaN this function will panic.
1492#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1493pub fn f64_suffixed(n: f64) -> Literal {
1494if !n.is_finite() {
1495{
::core::panicking::panic_fmt(format_args!("Invalid float literal {0}",
n));
};panic!("Invalid float literal {n}");
1496 }
1497Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1498 }
14991500/// String literal.
1501#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1502pub fn string(string: &str) -> Literal {
1503let escape = EscapeOptions {
1504 escape_single_quote: false,
1505 escape_double_quote: true,
1506 escape_nonascii: false,
1507 };
1508let repr = escape_bytes(string.as_bytes(), escape);
1509Literal::new(bridge::LitKind::Str, &repr, None)
1510 }
15111512/// Character literal.
1513#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1514pub fn character(ch: char) -> Literal {
1515let escape = EscapeOptions {
1516 escape_single_quote: true,
1517 escape_double_quote: false,
1518 escape_nonascii: false,
1519 };
1520let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1521Literal::new(bridge::LitKind::Char, &repr, None)
1522 }
15231524/// Byte character literal.
1525#[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1526pub fn byte_character(byte: u8) -> Literal {
1527let escape = EscapeOptions {
1528 escape_single_quote: true,
1529 escape_double_quote: false,
1530 escape_nonascii: true,
1531 };
1532let repr = escape_bytes(&[byte], escape);
1533Literal::new(bridge::LitKind::Byte, &repr, None)
1534 }
15351536/// Byte string literal.
1537#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1538pub fn byte_string(bytes: &[u8]) -> Literal {
1539let escape = EscapeOptions {
1540 escape_single_quote: false,
1541 escape_double_quote: true,
1542 escape_nonascii: true,
1543 };
1544let repr = escape_bytes(bytes, escape);
1545Literal::new(bridge::LitKind::ByteStr, &repr, None)
1546 }
15471548/// C string literal.
1549#[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1550pub fn c_string(string: &CStr) -> Literal {
1551let escape = EscapeOptions {
1552 escape_single_quote: false,
1553 escape_double_quote: true,
1554 escape_nonascii: false,
1555 };
1556let repr = escape_bytes(string.to_bytes(), escape);
1557Literal::new(bridge::LitKind::CStr, &repr, None)
1558 }
15591560/// Returns the span encompassing this literal.
1561#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1562pub fn span(&self) -> Span {
1563Span(self.0.span)
1564 }
15651566/// Configures the span associated for this literal.
1567#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1568pub fn set_span(&mut self, span: Span) {
1569self.0.span = span.0;
1570 }
15711572/// Returns a `Span` that is a subset of `self.span()` containing only the
1573 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1574 /// span is outside the bounds of `self`.
1575// FIXME(SergioBenitez): check that the byte range starts and ends at a
1576 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1577 // occur elsewhere when the source text is printed.
1578 // FIXME(SergioBenitez): there is no way for the user to know what
1579 // `self.span()` actually maps to, so this method can currently only be
1580 // called blindly. For example, `to_string()` for the character 'c' returns
1581 // "'\u{63}'"; there is no way for the user to know whether the source text
1582 // was 'c' or whether it was '\u{63}'.
1583#[unstable(feature = "proc_macro_span", issue = "54725")]
1584pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1585BridgeMethods::span_subspan(
1586self.0.span,
1587range.start_bound().cloned(),
1588range.end_bound().cloned(),
1589 )
1590 .map(Span)
1591 }
15921593fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1594self.0.symbol.with(|symbol| match self.0.suffix {
1595Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1596None => f(symbol, ""),
1597 })
1598 }
15991600/// Invokes the callback with a `&[&str]` consisting of each part of the
1601 /// literal's representation. This is done to allow the `ToString` and
1602 /// `Display` implementations to borrow references to symbol values, and
1603 /// both be optimized to reduce overhead.
1604fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1605/// Returns a string containing exactly `num` '#' characters.
1606 /// Uses a 256-character source string literal which is always safe to
1607 /// index with a `u8` index.
1608fn get_hashes_str(num: u8) -> &'static str {
1609const HASHES: &str = "\
1610 ################################################################\
1611 ################################################################\
1612 ################################################################\
1613 ################################################################\
1614 ";
1615const _: () = if !(HASHES.len() == 256) {
::core::panicking::panic("assertion failed: HASHES.len() == 256")
}assert!(HASHES.len() == 256);
1616&HASHES[..num as usize]
1617 }
16181619self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1620 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1621 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1622 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1623 bridge::LitKind::StrRaw(n) => {
1624let hashes = get_hashes_str(n);
1625f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1626 }
1627 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1628 bridge::LitKind::ByteStrRaw(n) => {
1629let hashes = get_hashes_str(n);
1630f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1631 }
1632 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1633 bridge::LitKind::CStrRaw(n) => {
1634let hashes = get_hashes_str(n);
1635f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1636 }
16371638 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1639f(&[symbol, suffix])
1640 }
1641 })
1642 }
16431644/// Returns the unescaped character value if the current literal is a byte character literal.
1645#[unstable(feature = "proc_macro_value", issue = "136652")]
1646pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1647self.0.symbol.with(|symbol| match self.0.kind {
1648 bridge::LitKind::Byte => unescape_byte(symbol)
1649 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1650_ => Err(ConversionErrorKind::InvalidLiteralKind),
1651 })
1652 }
16531654/// Returns the unescaped character value if the current literal is a character literal.
1655#[unstable(feature = "proc_macro_value", issue = "136652")]
1656pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1657self.0.symbol.with(|symbol| match self.0.kind {
1658 bridge::LitKind::Char => unescape_char(symbol)
1659 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1660_ => Err(ConversionErrorKind::InvalidLiteralKind),
1661 })
1662 }
16631664/// Returns the unescaped string value if the current literal is a string or a string literal.
1665#[unstable(feature = "proc_macro_value", issue = "136652")]
1666pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1667self.0.symbol.with(|symbol| match self.0.kind {
1668 bridge::LitKind::Str => {
1669if symbol.contains('\\') {
1670let mut buf = String::with_capacity(symbol.len());
1671let mut error = None;
1672// Force-inlining here is aggressive but the closure is
1673 // called on every char in the string, so it can be hot in
1674 // programs with many long strings containing escapes.
1675unescape_str(
1676symbol,
1677#[inline(always)]
1678|_, c| match c {
1679Ok(c) => buf.push(c),
1680Err(err) => {
1681if err.is_fatal() {
1682error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1683 }
1684 }
1685 },
1686 );
1687if let Some(error) = error { Err(error) } else { Ok(buf) }
1688 } else {
1689Ok(symbol.to_string())
1690 }
1691 }
1692 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1693_ => Err(ConversionErrorKind::InvalidLiteralKind),
1694 })
1695 }
16961697/// Returns the unescaped string value if the current literal is a c-string or a c-string
1698 /// literal.
1699#[unstable(feature = "proc_macro_value", issue = "136652")]
1700pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1701self.0.symbol.with(|symbol| match self.0.kind {
1702 bridge::LitKind::CStr => {
1703let mut error = None;
1704let mut buf = Vec::with_capacity(symbol.len());
17051706unescape_c_str(symbol, |_span, res| match res {
1707Ok(MixedUnit::Char(c)) => {
1708buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1709 }
1710Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1711Err(err) => {
1712if err.is_fatal() {
1713error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1714 }
1715 }
1716 });
1717if let Some(error) = error {
1718Err(error)
1719 } else {
1720buf.push(0);
1721Ok(buf)
1722 }
1723 }
1724 bridge::LitKind::CStrRaw(_) => {
1725// Raw strings have no escapes so we can convert the symbol
1726 // directly to a `Lrc<u8>` after appending the terminating NUL
1727 // char.
1728let mut buf = symbol.to_owned().into_bytes();
1729buf.push(0);
1730Ok(buf)
1731 }
1732_ => Err(ConversionErrorKind::InvalidLiteralKind),
1733 })
1734 }
17351736/// Returns the unescaped string value if the current literal is a byte string or a byte string
1737 /// literal.
1738#[unstable(feature = "proc_macro_value", issue = "136652")]
1739pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1740self.0.symbol.with(|symbol| match self.0.kind {
1741 bridge::LitKind::ByteStr => {
1742let mut buf = Vec::with_capacity(symbol.len());
1743let mut error = None;
17441745unescape_byte_str(symbol, |_, res| match res {
1746Ok(b) => buf.push(b),
1747Err(err) => {
1748if err.is_fatal() {
1749error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1750 }
1751 }
1752 });
1753if let Some(error) = error { Err(error) } else { Ok(buf) }
1754 }
1755 bridge::LitKind::ByteStrRaw(_) => {
1756// Raw strings have no escapes so we can convert the symbol
1757 // directly to a `Lrc<u8>`.
1758Ok(symbol.to_owned().into_bytes())
1759 }
1760_ => Err(ConversionErrorKind::InvalidLiteralKind),
1761 })
1762 }
17631764#[doc =
"Returns the unescaped `u8` value if the literal is a `u8` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn u8_value(&self) -> Result<u8, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"u8" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
u8::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `u16` value if the literal is a `u16` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn u16_value(&self) -> Result<u16, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"u16" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
u16::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `u32` value if the literal is a `u32` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn u32_value(&self) -> Result<u32, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"u32" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
u32::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `u64` value if the literal is a `u64` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn u64_value(&self) -> Result<u64, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"u64" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
u64::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `u128` value if the literal is a `u128` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn u128_value(&self) -> Result<u128, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"u128" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
u128::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `i8` value if the literal is a `i8` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn i8_value(&self) -> Result<i8, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"i8" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
i8::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `i16` value if the literal is a `i16` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn i16_value(&self) -> Result<i16, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"i16" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
i16::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `i32` value if the literal is a `i32` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn i32_value(&self) -> Result<i32, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"i32" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
i32::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `i64` value if the literal is a `i64` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn i64_value(&self) -> Result<i64, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"i64" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
i64::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `i128` value if the literal is a `i128` or if it\'s an \"unmarked\" integer which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn i128_value(&self) -> Result<i128, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Integer {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"i128" | "" => {
let symbol = strip_underscores(symbol);
let (number, base) = parse_number(&symbol);
i128::from_str_radix(&number,
base as
u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}integer_values! {
1765 u8 => u8_value,
1766 u16 => u16_value,
1767 u32 => u32_value,
1768 u64 => u64_value,
1769 u128 => u128_value,
1770 i8 => i8_value,
1771 i16 => i16_value,
1772 i32 => i32_value,
1773 i64 => i64_value,
1774 i128 => i128_value,
1775 }17761777#[doc =
"Returns the unescaped `f16` value if the literal is a `f16` or if it\'s an \"unmarked\" float which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn f16_value(&self) -> Result<f16, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Float {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"f16" | "" => {
let number = strip_underscores(symbol);
f16::from_str(&number).map_err(|_|
ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `f32` value if the literal is a `f32` or if it\'s an \"unmarked\" float which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn f32_value(&self) -> Result<f32, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Float {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"f32" | "" => {
let number = strip_underscores(symbol);
f32::from_str(&number).map_err(|_|
ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}
#[doc =
"Returns the unescaped `f64` value if the literal is a `f64` or if it\'s an \"unmarked\" float which doesn\'t overflow."]
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn f64_value(&self) -> Result<f64, ConversionErrorKind> {
if self.0.kind != bridge::LitKind::Float {
return Err(ConversionErrorKind::InvalidLiteralKind);
}
self.with_symbol_and_suffix(|symbol, suffix|
{
match suffix {
"f64" | "" => {
let number = strip_underscores(symbol);
f64::from_str(&number).map_err(|_|
ConversionErrorKind::InvalidLiteralKind)
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
}
})
}float_values! {
1778 f16 => f16_value,
1779 f32 => f32_value,
1780 f64 => f64_value,
1781// FIXME: `f128` doesn't implement `FromStr` for the moment so we cannot obtain it from
1782 // a `&str`. To be uncommented when it's added.
1783 // f128 => f128_value,
1784}1785}
17861787#[repr(u32)]
1788#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for Base { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Base {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Base { }Eq)]
1789enum Base {
1790 Decimal = 10,
1791 Binary = 2,
1792 Octal = 8,
1793 Hexadecimal = 16,
1794}
17951796fn parse_number(value: &str) -> (&str, Base) {
1797let mut iter = value.as_bytes().iter().copied();
1798let Some(first_digit) = iter.next() else {
1799return ("0", Base::Decimal);
1800 };
1801let Some(second_digit) = iter.next() else {
1802return (value, Base::Decimal);
1803 };
18041805let mut base = Base::Decimal;
1806if first_digit == b'0' {
1807// Attempt to parse encoding base.
1808match second_digit {
1809b'b' => {
1810base = Base::Binary;
1811 }
1812b'o' => {
1813base = Base::Octal;
1814 }
1815b'x' => {
1816base = Base::Hexadecimal;
1817 }
1818_ => {}
1819 }
1820 }
18211822let offset = if base == Base::Decimal { 0 } else { 2 };
18231824 (&value[offset..], base)
1825}
18261827fn strip_underscores(value_s: &str) -> Cow<'_, str> {
1828let value = value_s.as_bytes();
1829if value.iter().copied().all(|c| c != b'_' && c != b'f') {
1830return Cow::Borrowed(value_s);
1831 }
1832let mut output = String::with_capacity(value.len());
1833for c in value.iter().copied() {
1834if c != b'_' {
1835 output.push(c as char);
1836 }
1837 }
1838 Cow::Owned(output)
1839}
18401841/// Parse a single literal from its stringified representation.
1842///
1843/// In order to parse successfully, the input string must not contain anything
1844/// but the literal token. Specifically, it must not contain whitespace or
1845/// comments in addition to the literal.
1846///
1847/// The resulting literal token will have a `Span::call_site()` span.
1848///
1849/// NOTE: some errors may cause panics instead of returning `LexError`. We
1850/// reserve the right to change these errors into `LexError`s later.
1851#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1852impl FromStrfor Literal {
1853type Err = LexError;
18541855fn from_str(src: &str) -> Result<Self, LexError> {
1856match BridgeMethods::literal_from_str(src) {
1857Ok(literal) => Ok(Literal(literal)),
1858Err(msg) => Err(LexError(msg)),
1859 }
1860 }
1861}
18621863/// Prints the literal as a string that should be losslessly convertible
1864/// back into the same literal (except for possible rounding for floating point literals).
1865#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1866impl fmt::Displayfor Literal {
1867fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1868self.with_stringify_parts(|parts| {
1869for part in parts {
1870 fmt::Display::fmt(part, f)?;
1871 }
1872Ok(())
1873 })
1874 }
1875}
18761877#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1878impl fmt::Debugfor Literal {
1879fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1880f.debug_struct("Literal")
1881// format the kind on one line even in {:#?} mode
1882 .field("kind", &format_args!("{0:?}", self.0.kind)format_args!("{:?}", self.0.kind))
1883 .field("symbol", &self.0.symbol)
1884// format `Some("...")` on one line even in {:#?} mode
1885 .field("suffix", &format_args!("{0:?}", self.0.suffix)format_args!("{:?}", self.0.suffix))
1886 .field("span", &self.0.span)
1887 .finish()
1888 }
1889}
18901891#[unstable(
1892 feature = "proc_macro_tracked_path",
1893 issue = "99515",
1894 implied_by = "proc_macro_tracked_env"
1895)]
1896/// Functionality for adding environment state to the build dependency info.
1897pub mod tracked {
1898use std::env::{self, VarError};
1899use std::ffi::OsStr;
1900use std::path::Path;
19011902use crate::BridgeMethods;
19031904/// Retrieve an environment variable and add it to build dependency info.
1905 /// The build system executing the compiler will know that the variable was accessed during
1906 /// compilation, and will be able to rerun the build when the value of that variable changes.
1907 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1908 /// standard library, except that the argument must be UTF-8.
1909#[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1910pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1911let key: &str = key.as_ref();
1912let value = env::var(key);
1913BridgeMethods::track_env_var(key, value.as_deref().ok());
1914value1915 }
19161917/// Track a file or directory explicitly.
1918 ///
1919 /// Commonly used for tracking asset preprocessing.
1920#[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1921pub fn path<P: AsRef<Path>>(path: P) {
1922let path: &str = path.as_ref().to_str().unwrap();
1923BridgeMethods::track_path(path);
1924 }
1925}